defeatedFinales) {
+ this.defeatedFinales = defeatedFinales;
+ }
}
diff --git a/src/main/java/world/bentobox/aoneblock/events/PhaseFinaleEndEvent.java b/src/main/java/world/bentobox/aoneblock/events/PhaseFinaleEndEvent.java
new file mode 100644
index 00000000..3ab8c492
--- /dev/null
+++ b/src/main/java/world/bentobox/aoneblock/events/PhaseFinaleEndEvent.java
@@ -0,0 +1,70 @@
+package world.bentobox.aoneblock.events;
+
+import java.util.UUID;
+
+import org.bukkit.block.Block;
+import org.bukkit.event.HandlerList;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+
+import world.bentobox.bentobox.database.objects.Island;
+
+/**
+ * Fired when a phase finale ends, either because the boss was defeated or
+ * because it left (everyone died or went away, or the boss was removed).
+ * @author tastybento
+ */
+public class PhaseFinaleEndEvent extends AbstractMagicBlockEvent {
+
+ private static final HandlerList handlers = new HandlerList();
+ private final String phase;
+ private final boolean defeated;
+ private final boolean firstTime;
+
+ @Override
+ public HandlerList getHandlers() {
+ return getHandlerList();
+ }
+
+ public static HandlerList getHandlerList() {
+ return handlers;
+ }
+
+ /**
+ * @param island - island
+ * @param playerUUID - player who killed the boss, if any
+ * @param block - the magic block
+ * @param phase - name of the phase that is ending
+ * @param defeated - true if the boss was defeated
+ * @param firstTime - true if this is the first time this island defeated this boss
+ */
+ public PhaseFinaleEndEvent(@NonNull Island island, @Nullable UUID playerUUID, @NonNull Block block,
+ @NonNull String phase, boolean defeated, boolean firstTime) {
+ super(island, playerUUID, block);
+ this.phase = phase;
+ this.defeated = defeated;
+ this.firstTime = firstTime;
+ }
+
+ /**
+ * @return the name of the phase that is ending
+ */
+ @NonNull
+ public String getPhase() {
+ return phase;
+ }
+
+ /**
+ * @return true if the boss was defeated, false if the finale was abandoned
+ */
+ public boolean isDefeated() {
+ return defeated;
+ }
+
+ /**
+ * @return true if this is the first time the island defeated this boss
+ */
+ public boolean isFirstTime() {
+ return firstTime;
+ }
+}
diff --git a/src/main/java/world/bentobox/aoneblock/events/PhaseFinaleStartEvent.java b/src/main/java/world/bentobox/aoneblock/events/PhaseFinaleStartEvent.java
new file mode 100644
index 00000000..be7a2b3a
--- /dev/null
+++ b/src/main/java/world/bentobox/aoneblock/events/PhaseFinaleStartEvent.java
@@ -0,0 +1,75 @@
+package world.bentobox.aoneblock.events;
+
+import java.util.UUID;
+
+import org.bukkit.block.Block;
+import org.bukkit.event.Cancellable;
+import org.bukkit.event.HandlerList;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+
+import world.bentobox.aoneblock.oneblocks.PhaseFinale;
+import world.bentobox.bentobox.database.objects.Island;
+
+/**
+ * Fired when a phase finale is about to start, before the boss spawns.
+ * Cancelling it waives the finale: no boss spawns and the island may move on
+ * to the next phase.
+ * @author tastybento
+ */
+public class PhaseFinaleStartEvent extends AbstractMagicBlockEvent implements Cancellable {
+
+ private static final HandlerList handlers = new HandlerList();
+ private final String phase;
+ private final PhaseFinale finale;
+ private boolean cancelled;
+
+ @Override
+ public HandlerList getHandlers() {
+ return getHandlerList();
+ }
+
+ public static HandlerList getHandlerList() {
+ return handlers;
+ }
+
+ /**
+ * @param island - island
+ * @param playerUUID - player who triggered the finale
+ * @param block - the magic block
+ * @param phase - name of the phase that is ending
+ * @param finale - the finale definition
+ */
+ public PhaseFinaleStartEvent(@NonNull Island island, @Nullable UUID playerUUID, @NonNull Block block,
+ @NonNull String phase, @NonNull PhaseFinale finale) {
+ super(island, playerUUID, block);
+ this.phase = phase;
+ this.finale = finale;
+ }
+
+ /**
+ * @return the name of the phase that is ending
+ */
+ @NonNull
+ public String getPhase() {
+ return phase;
+ }
+
+ /**
+ * @return the finale definition
+ */
+ @NonNull
+ public PhaseFinale getFinale() {
+ return finale;
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return cancelled;
+ }
+
+ @Override
+ public void setCancelled(boolean cancel) {
+ this.cancelled = cancel;
+ }
+}
diff --git a/src/main/java/world/bentobox/aoneblock/listeners/BlockListener.java b/src/main/java/world/bentobox/aoneblock/listeners/BlockListener.java
index 8fc63849..f94a15c9 100644
--- a/src/main/java/world/bentobox/aoneblock/listeners/BlockListener.java
+++ b/src/main/java/world/bentobox/aoneblock/listeners/BlockListener.java
@@ -121,6 +121,11 @@ private record BrushSession(BukkitTask task, Block block) {}
*/
private final WarningSounder warningSounder;
+ /**
+ * Runs the boss fights that end phases.
+ */
+ private final FinaleListener finaleListener;
+
/**
* How many blocks ahead the queue should look when populating.
*/
@@ -171,6 +176,7 @@ public BlockListener(@NonNull AOneBlock addon) {
oneBlocksManager = addon.getOneBlockManager();
check = new CheckPhase(addon, this);
warningSounder = new WarningSounder(addon);
+ finaleListener = new FinaleListener(addon);
}
/**
@@ -483,6 +489,11 @@ private ProcessPhaseResult processPhase(Cancellable e, Island i, OneBlockIslands
boolean isCurrPhaseNew = !is.getPhaseName().equalsIgnoreCase(currPhaseName);
if (isCurrPhaseNew) {
+ // The old phase's boss, if it has one, must be defeated first.
+ if (finaleListener.gate(i, is, player, block)) {
+ e.setCancelled(true);
+ return new ProcessPhaseResult(phase, true, 0);
+ }
// Check if the player meets the requirements for the new phase.
if (check.phaseRequirementsFail(player, i, is, phase, world)) {
e.setCancelled(true);
@@ -566,6 +577,9 @@ private void processHologramAndWarnings(Island i, OneBlockIslands is, OneBlockPh
if (addon.getSettings().getMobWarning() > 0) {
warningSounder.play(is, block);
}
+ if (addon.getSettings().isPhaseFinales() && phase.getFinale() != null) {
+ warningSounder.omen(block, phase.getFinale(), oneBlocksManager.getNextPhaseBlocks(is));
+ }
}
/**
@@ -589,6 +603,8 @@ private void processNextBlock(Cancellable e, Island i, Player player, Block bloc
}
is.incrementBlockNumber();
+ // If that was the last block of the phase, its boss is next
+ finaleListener.arm(is, phaseResult.phase);
handleBlockBreak(e, i, player, block, nextBlock);
}
@@ -1086,6 +1102,20 @@ public OneBlocksManager getOneBlocksManager() {
return oneBlocksManager;
}
+ /**
+ * @return the phase checker
+ */
+ CheckPhase getCheckPhase() {
+ return check;
+ }
+
+ /**
+ * @return the listener that runs phase finales
+ */
+ public FinaleListener getFinaleListener() {
+ return finaleListener;
+ }
+
/**
* Saves the island progress to the database async
*
diff --git a/src/main/java/world/bentobox/aoneblock/listeners/BossBarListener.java b/src/main/java/world/bentobox/aoneblock/listeners/BossBarListener.java
index 196176f4..ebee6a61 100644
--- a/src/main/java/world/bentobox/aoneblock/listeners/BossBarListener.java
+++ b/src/main/java/world/bentobox/aoneblock/listeners/BossBarListener.java
@@ -1,5 +1,9 @@
package world.bentobox.aoneblock.listeners;
+import world.bentobox.aoneblock.events.PhaseFinaleEndEvent;
+import world.bentobox.aoneblock.events.PhaseFinaleStartEvent;
+import world.bentobox.aoneblock.oneblocks.OneBlockPhase;
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@@ -55,6 +59,34 @@ public void onBreakBlockEvent(MagicBlockEvent e) {
tryToShowActionBar(e.getPlayerUUID(), e.getIsland());
}
+ /**
+ * The boss has its own health bar, so the phase bar steps aside for the fight.
+ * @param e event
+ */
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void onFinaleStart(PhaseFinaleStartEvent e) {
+ BossBar bar = islandBossBars.remove(e.getIsland());
+ if (bar != null) {
+ bar.removeAll();
+ }
+ }
+
+ /**
+ * Bring the phase bar back as soon as the fight is over, whichever way it went.
+ * @param e event
+ */
+ @EventHandler(priority = EventPriority.MONITOR)
+ public void onFinaleEnd(PhaseFinaleEndEvent e) {
+ Island island = e.getIsland();
+ if (island.getWorld() == null) {
+ return;
+ }
+ island.getWorld().getPlayers().stream().filter(p -> island.onIsland(p.getLocation())).forEach(p -> {
+ tryToShowActionBar(p.getUniqueId(), island);
+ tryToShowBossBar(p.getUniqueId(), island);
+ });
+ }
+
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onEnterIsland(IslandEnterEvent event) {
if (addon.inWorld(event.getIsland().getWorld())) {
@@ -93,6 +125,58 @@ public static Component bukkitToAdventure(String text) {
return Util.parseMiniMessageOrLegacy(text);
}
+ /**
+ * @param obi island data
+ * @return the plain name of the phase boss this island still has to defeat, or
+ * null if there is none
+ */
+ private String pendingBoss(OneBlockIslands obi) {
+ String pending = obi.getFinalePending();
+ if (pending == null || pending.isEmpty() || !addon.getSettings().isPhaseFinales()) {
+ return null;
+ }
+ return addon.getOneBlockManager().getPhase(pending).map(OneBlockPhase::getFinale)
+ .map(f -> PlainTextComponentSerializer.plainText()
+ .serialize(Util.parseMiniMessageOrLegacy(f.name())))
+ .orElse(null);
+ }
+
+ /**
+ * @param island island
+ * @return true if the phase boss is alive on this island right now
+ */
+ private boolean isFighting(Island island) {
+ FinaleListener finales = addon.getFinaleListener();
+ return finales != null && finales.isActive(island);
+ }
+
+ /**
+ * While a phase boss is still to be defeated, the block count is already in the
+ * next phase, so the bar names the boss instead of showing that phase's progress.
+ * While the boss is alive it has its own health bar and this one steps aside.
+ *
+ * @return true if the bar was handled here
+ */
+ private boolean showPendingBoss(BossBar bar, User user, UUID uuid, Island island, OneBlockIslands obi) {
+ String boss = pendingBoss(obi);
+ if (boss == null) {
+ return false;
+ }
+ if (isFighting(island)) {
+ islandBossBars.remove(island);
+ bar.removeAll();
+ return true;
+ }
+ bar.setProgress(1D);
+ bar.setTitle(user.getTranslationOrNothing("aoneblock.finale.pending", "[name]", boss));
+ Player player = Bukkit.getPlayer(uuid);
+ if (!bar.getPlayers().contains(player)) {
+ bar.addPlayer(player);
+ }
+ islandBossBars.put(island, bar);
+ return true;
+ }
+
private void tryToShowActionBar(UUID uuid, Island island) {
// The listener is registered whenever either the boss bar or action bar flag is
// registered, so the global setting must be checked here as well as the flag
@@ -115,6 +199,17 @@ private void tryToShowActionBar(UUID uuid, Island island) {
@NonNull
OneBlockIslands obi = addon.getOneBlocksIsland(island);
+ // A boss stands between this island and the next phase
+ String boss = pendingBoss(obi);
+ if (boss != null && isFighting(island)) {
+ // The boss has its own health bar
+ return;
+ }
+ if (boss != null) {
+ player.sendActionBar(
+ bukkitToAdventure(user.getTranslation("aoneblock.finale.pending", "[name]", boss)));
+ return;
+ }
// --- Create the Action Bar Component ---
int numBlocksToGo = addon.getOneBlockManager().getNextPhaseBlocks(obi);
int phaseBlocks = addon.getOneBlockManager().getPhaseBlocks(obi);
@@ -180,6 +275,9 @@ private void tryToShowBossBar(UUID uuid, Island island) {
@NonNull
OneBlockIslands obi = addon.getOneBlocksIsland(island);
+ if (showPendingBoss(bar, user, uuid, island, obi)) {
+ return;
+ }
// Set progress
bar.setProgress(addon.getOneBlockManager().getPercentageDone(obi) / 100);
int numBlocksToGo = addon.getOneBlockManager().getNextPhaseBlocks(obi);
diff --git a/src/main/java/world/bentobox/aoneblock/listeners/FinaleListener.java b/src/main/java/world/bentobox/aoneblock/listeners/FinaleListener.java
new file mode 100644
index 00000000..67f93a1f
--- /dev/null
+++ b/src/main/java/world/bentobox/aoneblock/listeners/FinaleListener.java
@@ -0,0 +1,684 @@
+package world.bentobox.aoneblock.listeners;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Difficulty;
+import org.bukkit.GameMode;
+import org.bukkit.Location;
+import org.bukkit.Particle;
+import org.bukkit.Sound;
+import org.bukkit.World;
+import org.bukkit.attribute.Attribute;
+import org.bukkit.attribute.AttributeInstance;
+import org.bukkit.block.Block;
+import org.bukkit.entity.Entity;
+import org.bukkit.entity.EntityType;
+import org.bukkit.entity.Giant;
+import org.bukkit.entity.Hoglin;
+import org.bukkit.entity.LivingEntity;
+import org.bukkit.entity.Mob;
+import org.bukkit.entity.PiglinAbstract;
+import org.bukkit.entity.Player;
+import org.bukkit.entity.Projectile;
+import org.bukkit.entity.Tameable;
+import org.bukkit.entity.Warden;
+import org.bukkit.event.EventHandler;
+import org.bukkit.event.EventPriority;
+import org.bukkit.event.Listener;
+import org.bukkit.event.block.BlockIgniteEvent;
+import org.bukkit.event.entity.EntityChangeBlockEvent;
+import org.bukkit.event.entity.EntityCombustByBlockEvent;
+import org.bukkit.event.entity.EntityCombustByEntityEvent;
+import org.bukkit.event.entity.EntityCombustEvent;
+import org.bukkit.event.entity.EntityDamageByEntityEvent;
+import org.bukkit.event.entity.EntityDamageEvent;
+import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
+import org.bukkit.event.entity.EntityDeathEvent;
+import org.bukkit.event.entity.EntityExplodeEvent;
+import org.bukkit.event.entity.PlayerDeathEvent;
+import org.bukkit.inventory.ItemStack;
+import org.bukkit.scheduler.BukkitTask;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+
+import net.kyori.adventure.bossbar.BossBar;
+import net.kyori.adventure.text.Component;
+import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
+import world.bentobox.aoneblock.AOneBlock;
+import world.bentobox.aoneblock.dataobjects.OneBlockIslands;
+import world.bentobox.aoneblock.events.PhaseFinaleEndEvent;
+import world.bentobox.aoneblock.events.PhaseFinaleStartEvent;
+import world.bentobox.aoneblock.oneblocks.OneBlockPhase;
+import world.bentobox.aoneblock.oneblocks.PhaseFinale;
+import world.bentobox.bentobox.api.events.island.IslandDeleteEvent;
+import world.bentobox.bentobox.api.events.island.IslandResettedEvent;
+import world.bentobox.bentobox.api.user.User;
+import world.bentobox.bentobox.database.objects.Island;
+import world.bentobox.bentobox.util.Util;
+
+/**
+ * Runs phase finales: the boss that must be defeated at the end of a phase
+ * before the magic block moves on to the next one.
+ *
+ * A finale is armed when the last block of a phase is mined, and
+ * gates the next break of the magic block until the boss is dead. The
+ * armed state is persisted in {@link OneBlockIslands}; the boss itself is not,
+ * so a restart, an empty island or a mob-clearing plugin only ever sends the
+ * fight back to "hit the block to summon the boss", never to a free pass.
+ *
+ * @author tastybento
+ */
+public class FinaleListener implements Listener {
+
+ /** Ticks between checks of each running finale. */
+ static final long TICK_PERIOD = 10L;
+ /** How many checks an island may be empty of fighters before the boss leaves. */
+ static final int EMPTY_CHECKS = 20;
+ /** Boss health scales for up to this many players. */
+ static final int MAX_SCALED_PLAYERS = 4;
+ /** Extra health per additional player, as a fraction of base health. */
+ static final double HEALTH_PER_PLAYER = 0.5D;
+ /** Health reduction per consecutive loss, as a fraction of base health. */
+ static final double MERCY_PER_FAIL = 0.1D;
+ /** The boss never drops below this fraction of its health through mercy. */
+ static final double MERCY_FLOOR = 0.5D;
+
+ private static final String NAME = "[name]";
+
+ private final AOneBlock addon;
+ /** Running finales by island unique id. */
+ private final Map active = new HashMap<>();
+ /** Running finales by boss entity id. */
+ private final Map byBoss = new HashMap<>();
+ /** Running finales by minion entity id. */
+ private final Map byMinion = new HashMap<>();
+ private BukkitTask task;
+
+ /**
+ * A finale in progress.
+ */
+ static class ActiveFinale {
+ final Island island;
+ final OneBlockIslands is;
+ final String phaseName;
+ final PhaseFinale finale;
+ final Block block;
+ final LivingEntity boss;
+ final Set minions = new HashSet<>();
+ final Set viewers = new HashSet<>();
+ final BossBar bar;
+ final String plainName;
+ boolean playerDied;
+ int emptyChecks;
+
+ ActiveFinale(Island island, OneBlockIslands is, String phaseName, PhaseFinale finale, Block block,
+ LivingEntity boss, Component name) {
+ this.island = island;
+ this.is = is;
+ this.phaseName = phaseName;
+ this.finale = finale;
+ this.block = block;
+ this.boss = boss;
+ this.bar = BossBar.bossBar(name, 1F, BossBar.Color.RED, BossBar.Overlay.PROGRESS);
+ this.plainName = PlainTextComponentSerializer.plainText().serialize(name);
+ }
+ }
+
+ /**
+ * @param addon - addon
+ */
+ public FinaleListener(@NonNull AOneBlock addon) {
+ this.addon = addon;
+ }
+
+ // ---------------------------------------------------------------------
+ // Section: Arming and gating, called by the BlockListener
+ // ---------------------------------------------------------------------
+
+ /**
+ * Called after the block count goes up. Arms the finale if that was the last
+ * block of a phase that has one.
+ *
+ * @param is - island data, block number already incremented
+ * @param phase - the phase the mined block belonged to
+ */
+ public void arm(@NonNull OneBlockIslands is, @NonNull OneBlockPhase phase) {
+ if (!addon.getSettings().isPhaseFinales() || phase.getFinale() == null || phase.getPhaseName() == null) {
+ return;
+ }
+ if (addon.getOneBlockManager().getPhase(is.getBlockNumber()) != phase) {
+ is.setFinalePending(phase.getPhaseName());
+ }
+ }
+
+ /**
+ * Called when the magic block is about to move to a new phase. Starts the
+ * pending finale if there is one.
+ *
+ * @param island - island
+ * @param is - island data
+ * @param player - player breaking the block, or null if it is not a player
+ * @param block - the magic block
+ * @return true if the break must be cancelled because a boss stands in the way
+ */
+ public boolean gate(@NonNull Island island, @NonNull OneBlockIslands is, @Nullable Player player,
+ @NonNull Block block) {
+ String pending = is.getFinalePending();
+ if (pending.isEmpty()) {
+ return false;
+ }
+ PhaseFinale finale = addon.getOneBlockManager().getPhase(pending).map(OneBlockPhase::getFinale).orElse(null);
+ if (!addon.getSettings().isPhaseFinales() || finale == null || !pending.equalsIgnoreCase(is.getPhaseName())
+ || block.getWorld().getDifficulty() == Difficulty.PEACEFUL) {
+ // Nothing to fight, e.g., finales were turned off or the phase was edited
+ waive(is);
+ return false;
+ }
+ ActiveFinale running = active.get(island.getUniqueId());
+ if (running != null) {
+ if (player != null) {
+ User.getInstance(player).notify("aoneblock.finale.defeat-boss", NAME, running.plainName);
+ }
+ return true;
+ }
+ if (player == null || player.hasMetadata("NPC")) {
+ // Minions cannot summon the boss
+ return true;
+ }
+ PhaseFinaleStartEvent event = new PhaseFinaleStartEvent(island, player.getUniqueId(), block, pending, finale);
+ Bukkit.getPluginManager().callEvent(event);
+ if (event.isCancelled()) {
+ waive(is);
+ return false;
+ }
+ if (!start(island, is, pending, finale, block, player)) {
+ // The boss could not be spawned. Never lock an island behind a boss that is not there.
+ waive(is);
+ return false;
+ }
+ return true;
+ }
+
+ private void waive(OneBlockIslands is) {
+ is.setFinalePending("");
+ is.setFinaleFails(0);
+ }
+
+ /**
+ * Drop any pending or running finale for this island without a result. Used
+ * when an admin or player moves the block count.
+ * @param island - island
+ * @param is - island data
+ */
+ public void clear(@NonNull Island island, @NonNull OneBlockIslands is) {
+ waive(is);
+ ActiveFinale f = active.get(island.getUniqueId());
+ if (f != null) {
+ remove(f);
+ }
+ }
+
+ // ---------------------------------------------------------------------
+ // Section: The fight
+ // ---------------------------------------------------------------------
+
+ private boolean start(Island island, OneBlockIslands is, String phaseName, PhaseFinale finale, Block block,
+ Player summoner) {
+ World world = block.getWorld();
+ Location home = home(block);
+ Entity entity = world.spawnEntity(home, finale.boss());
+ if (!(entity instanceof LivingEntity boss) || !entity.isValid()) {
+ entity.remove();
+ addon.logWarning("Could not spawn finale boss " + finale.boss() + " for phase " + phaseName);
+ return false;
+ }
+ List fighters = fighters(island, world);
+ Component name = Util.parseMiniMessageOrLegacy(finale.name());
+ ActiveFinale f = new ActiveFinale(island, is, phaseName, finale, block, boss, name);
+
+ // Dress the boss
+ boss.customName(name);
+ boss.setCustomNameVisible(true);
+ boss.setPersistent(false);
+ boss.setRemoveWhenFarAway(false);
+ setAttribute(boss, Attribute.SCALE, finale.scale());
+ double health = scaledHealth(finale.health(), fighters.size(), is.getFinaleFails());
+ setAttribute(boss, Attribute.MAX_HEALTH, health);
+ AttributeInstance max = boss.getAttribute(Attribute.MAX_HEALTH);
+ if (max != null) {
+ // The server may cap max health, so read it back
+ boss.setHealth(max.getValue());
+ }
+ if (finale.damage() > 0) {
+ setAttribute(boss, Attribute.ATTACK_DAMAGE, finale.damage());
+ }
+ if (finale.speed() > 0) {
+ setAttribute(boss, Attribute.MOVEMENT_SPEED, finale.speed());
+ }
+ if (boss instanceof Giant giant) {
+ try {
+ GiantAttackGoal.apply(addon.getPlugin(), giant);
+ } catch (LinkageError | RuntimeException e) {
+ addon.logWarning("Giant bosses need Paper's mob goal API to fight back: " + e.getMessage());
+ }
+ }
+ prepare(boss);
+ provoke(boss, summoner);
+ if (addon.getSettings().isClearBlocks()) {
+ new MakeSpace(addon).makeSpace(boss, home);
+ }
+
+ // Minions
+ finale.minions().forEach((type, count) -> spawnMinions(f, type, count, home));
+
+ // Register
+ active.put(island.getUniqueId(), f);
+ byBoss.put(boss.getUniqueId(), f);
+ if (task == null) {
+ task = Bukkit.getScheduler().runTaskTimer(addon.getPlugin(), this::tickAll, TICK_PERIOD, TICK_PERIOD);
+ }
+
+ // Announce
+ world.strikeLightningEffect(home);
+ world.playSound(home, Sound.EVENT_RAID_HORN, 64F, 1F);
+ fighters.forEach(p -> {
+ show(f, p);
+ User.getInstance(p).sendMessage("aoneblock.finale.start", NAME, f.plainName);
+ });
+ return true;
+ }
+
+ private void spawnMinions(ActiveFinale f, EntityType type, int count, Location home) {
+ for (int i = 0; i < count; i++) {
+ Entity e = home.getWorld().spawnEntity(home, type);
+ if (!e.isValid()) {
+ continue;
+ }
+ e.setPersistent(false);
+ prepare(e);
+ f.minions.add(e.getUniqueId());
+ byMinion.put(e.getUniqueId(), f);
+ }
+ }
+
+ /**
+ * Boss health for the number of players fighting and the number of
+ * consecutive losses.
+ *
+ * @param base - base health from the phase file
+ * @param players - number of players on the island
+ * @param fails - consecutive losses
+ * @return health
+ */
+ static double scaledHealth(double base, int players, int fails) {
+ int extra = Math.clamp(players, 1, MAX_SCALED_PLAYERS) - 1;
+ double mercy = Math.max(MERCY_FLOOR, 1D - MERCY_PER_FAIL * Math.max(0, fails));
+ return base * (1D + HEALTH_PER_PLAYER * extra) * mercy;
+ }
+
+ /**
+ * Stops nether mobs from zombifying in the overworld part-way through a fight.
+ */
+ private static void prepare(Entity entity) {
+ if (entity instanceof PiglinAbstract piglin) {
+ piglin.setImmuneToZombification(true);
+ } else if (entity instanceof Hoglin hoglin) {
+ hoglin.setImmuneToZombification(true);
+ }
+ }
+
+ /**
+ * Point the boss at a player.
+ */
+ private static void provoke(LivingEntity boss, Player player) {
+ if (boss instanceof Warden warden) {
+ // Wardens ignore targets they are not angry at, and dig away when calm
+ warden.setAnger(player, 150);
+ }
+ if (boss instanceof Mob mob) {
+ mob.setTarget(player);
+ }
+ }
+
+ private static void setAttribute(LivingEntity entity, Attribute attribute, double value) {
+ AttributeInstance instance = entity.getAttribute(attribute);
+ if (instance != null) {
+ instance.setBaseValue(value);
+ }
+ }
+
+ private static Location home(Block block) {
+ return block.getLocation().add(0.5D, 1D, 0.5D);
+ }
+
+ /**
+ * @return living, non-spectating players inside the island's protected area
+ */
+ private List fighters(Island island, World world) {
+ return world.getPlayers().stream().filter(p -> !p.isDead() && p.getGameMode() != GameMode.SPECTATOR)
+ .filter(p -> island.onIsland(p.getLocation())).toList();
+ }
+
+ private void show(ActiveFinale f, Player p) {
+ if (f.viewers.add(p.getUniqueId())) {
+ p.showBossBar(f.bar);
+ }
+ }
+
+ private void hideAll(ActiveFinale f) {
+ f.viewers.stream().map(Bukkit::getPlayer).filter(java.util.Objects::nonNull)
+ .forEach(p -> p.hideBossBar(f.bar));
+ f.viewers.clear();
+ }
+
+ void tickAll() {
+ new ArrayList<>(active.values()).forEach(this::tick);
+ if (active.isEmpty() && task != null) {
+ task.cancel();
+ task = null;
+ }
+ }
+
+ private void tick(ActiveFinale f) {
+ LivingEntity boss = f.boss;
+ if (!boss.isValid()) {
+ // Removed by something other than a kill. Never a win.
+ abandon(f);
+ return;
+ }
+ List fighters = fighters(f.island, f.block.getWorld());
+ if (fighters.isEmpty()) {
+ if (++f.emptyChecks >= EMPTY_CHECKS) {
+ abandon(f);
+ }
+ return;
+ }
+ f.emptyChecks = 0;
+
+ // Leash
+ Location loc = boss.getLocation();
+ if (!f.island.onIsland(loc) || (f.finale.voidRespawn() && loc.getY() < loc.getWorld().getMinHeight())) {
+ recall(f);
+ }
+
+ // Boss bar
+ AttributeInstance max = boss.getAttribute(Attribute.MAX_HEALTH);
+ if (max != null && max.getValue() > 0) {
+ f.bar.progress((float) Math.clamp(boss.getHealth() / max.getValue(), 0D, 1D));
+ }
+ Set present = new HashSet<>();
+ fighters.forEach(p -> {
+ present.add(p.getUniqueId());
+ show(f, p);
+ });
+ f.viewers.removeIf(uuid -> {
+ if (present.contains(uuid)) {
+ return false;
+ }
+ Optional.ofNullable(Bukkit.getPlayer(uuid)).ifPresent(p -> p.hideBossBar(f.bar));
+ return true;
+ });
+
+ // Keep the boss interested
+ if (boss instanceof Mob mob && mob.getTarget() == null) {
+ Location bl = boss.getLocation();
+ fighters.stream().filter(p -> p.getGameMode() != GameMode.CREATIVE)
+ .min((a, b) -> Double.compare(a.getLocation().distanceSquared(bl),
+ b.getLocation().distanceSquared(bl)))
+ .ifPresent(p -> provoke(mob, p));
+ }
+ }
+
+ /**
+ * Bring the boss back to the magic block.
+ */
+ private void recall(ActiveFinale f) {
+ Location home = home(f.block);
+ f.boss.setFallDistance(0F);
+ f.boss.teleport(home);
+ home.getWorld().playSound(home, Sound.ENTITY_ENDERMAN_TELEPORT, 2F, 0.5F);
+ home.getWorld().spawnParticle(Particle.PORTAL, home, 60, 0.5D, 1D, 0.5D);
+ }
+
+ /**
+ * The boss leaves without being beaten.
+ */
+ private void abandon(ActiveFinale f) {
+ if (f.playerDied) {
+ f.is.setFinaleFails(f.is.getFinaleFails() + 1);
+ }
+ remove(f);
+ fighters(f.island, f.block.getWorld())
+ .forEach(p -> User.getInstance(p).sendMessage("aoneblock.finale.retreat", NAME, f.plainName));
+ Bukkit.getPluginManager()
+ .callEvent(new PhaseFinaleEndEvent(f.island, null, f.block, f.phaseName, false, false));
+ }
+
+ private void win(ActiveFinale f, @Nullable Player killer) {
+ boolean firstTime = f.is.getDefeatedFinales().add(f.phaseName);
+ f.is.setFinalePending("");
+ f.is.setFinaleFails(0);
+ remove(f);
+
+ World world = f.block.getWorld();
+ Location home = home(f.block);
+ f.finale.drops().forEach((material, amount) -> {
+ int stack = Math.max(1, material.getMaxStackSize());
+ int left = amount;
+ while (left > 0) {
+ int size = Math.min(left, stack);
+ world.dropItem(home, new ItemStack(material, size));
+ left -= size;
+ }
+ });
+ world.playSound(home, Sound.UI_TOAST_CHALLENGE_COMPLETE, 2F, 1F);
+ world.spawnParticle(Particle.TOTEM_OF_UNDYING, home, 80, 0.5D, 1D, 0.5D, 0.4D);
+
+ // Commands run as the killer, or the owner if there is no killer
+ User user = killer != null ? User.getInstance(killer) : addon.getPlayers().getUser(f.island.getOwner());
+ if (user != null) {
+ CheckPhase check = addon.getBlockListener().getCheckPhase();
+ String number = addon.getOneBlockManager().getPhase(f.phaseName).map(OneBlockPhase::getBlockNumber)
+ .orElse("");
+ Util.runCommands(user, check.replacePlaceholders(killer, f.phaseName, number, f.island, f.finale.commands()),
+ "Commands run for defeating the boss of " + f.phaseName);
+ if (firstTime) {
+ Util.runCommands(user,
+ check.replacePlaceholders(killer, f.phaseName, number, f.island, f.finale.firstTimeCommands()),
+ "Commands run for first time defeating the boss of " + f.phaseName);
+ }
+ }
+ fighters(f.island, world)
+ .forEach(p -> User.getInstance(p).sendMessage("aoneblock.finale.defeated", NAME, f.plainName));
+ Bukkit.getPluginManager().callEvent(new PhaseFinaleEndEvent(f.island,
+ killer == null ? null : killer.getUniqueId(), f.block, f.phaseName, true, firstTime));
+ addon.getBlockListener().saveIsland(f.island);
+ }
+
+ /**
+ * Take the finale's entities and boss bar out of the world and forget it.
+ */
+ private void remove(ActiveFinale f) {
+ active.remove(f.island.getUniqueId());
+ byBoss.remove(f.boss.getUniqueId());
+ if (f.boss.isValid()) {
+ f.boss.remove();
+ }
+ f.minions.forEach(uuid -> {
+ byMinion.remove(uuid);
+ Entity e = Bukkit.getEntity(uuid);
+ if (e != null) {
+ e.getWorld().spawnParticle(Particle.POOF, e.getLocation(), 10, 0.3D, 0.5D, 0.3D, 0.02D);
+ e.remove();
+ }
+ });
+ f.minions.clear();
+ hideAll(f);
+ }
+
+ /**
+ * Remove every running finale. Called when the addon is disabled.
+ */
+ public void onDisable() {
+ new ArrayList<>(active.values()).forEach(this::remove);
+ if (task != null) {
+ task.cancel();
+ task = null;
+ }
+ }
+
+ /**
+ * @param island - island
+ * @return true if a boss is currently alive on this island
+ */
+ public boolean isActive(@NonNull Island island) {
+ return active.containsKey(island.getUniqueId());
+ }
+
+ // ---------------------------------------------------------------------
+ // Section: Listeners
+ // ---------------------------------------------------------------------
+
+ /**
+ * Only players can hurt a boss. This shuts out suffocation boxes, lava, drop
+ * traps and grinders.
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+ public void onBossDamage(EntityDamageEvent e) {
+ ActiveFinale f = byBoss.get(e.getEntity().getUniqueId());
+ if (f == null) {
+ return;
+ }
+ if (e.getCause() == DamageCause.VOID) {
+ if (f.finale.voidRespawn()) {
+ e.setCancelled(true);
+ recall(f);
+ }
+ return;
+ }
+ if (e.getCause() == DamageCause.KILL
+ || (e instanceof EntityDamageByEntityEvent ee && isPlayerDamage(ee.getDamager()))) {
+ return;
+ }
+ e.setCancelled(true);
+ }
+
+ private static boolean isPlayerDamage(Entity damager) {
+ return damager instanceof Player || (damager instanceof Projectile p && p.getShooter() instanceof Player)
+ || (damager instanceof Tameable t && t.getOwner() instanceof Player);
+ }
+
+ /**
+ * Boss death is the win.
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void onDeath(EntityDeathEvent e) {
+ UUID uuid = e.getEntity().getUniqueId();
+ ActiveFinale f = byBoss.get(uuid);
+ if (f != null) {
+ win(f, e.getEntity().getKiller());
+ return;
+ }
+ f = byMinion.remove(uuid);
+ if (f != null) {
+ f.minions.remove(uuid);
+ }
+ }
+
+ /**
+ * Track deaths so that a lost fight makes the next attempt a little easier.
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void onPlayerDeath(PlayerDeathEvent e) {
+ if (active.isEmpty()) {
+ return;
+ }
+ Location loc = e.getEntity().getLocation();
+ active.values().stream().filter(f -> f.island.onIsland(loc)).forEach(f -> f.playerDied = true);
+ }
+
+ /**
+ * Finale mobs never change blocks.
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+ public void onChangeBlock(EntityChangeBlockEvent e) {
+ if (isFinaleEntity(e.getEntity())) {
+ e.setCancelled(true);
+ }
+ }
+
+ /**
+ * Finale mobs' explosions hurt players, not islands.
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+ public void onExplode(EntityExplodeEvent e) {
+ if (isFinaleEntity(e.getEntity())) {
+ e.blockList().clear();
+ }
+ }
+
+ /**
+ * Finale mobs' fireballs do not set the island alight.
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+ public void onIgnite(BlockIgniteEvent e) {
+ if (e.getIgnitingEntity() != null && isFinaleEntity(e.getIgnitingEntity())) {
+ e.setCancelled(true);
+ }
+ }
+
+ /**
+ * Finale mobs do not burn in daylight.
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
+ public void onCombust(EntityCombustEvent e) {
+ if (!(e instanceof EntityCombustByEntityEvent) && !(e instanceof EntityCombustByBlockEvent)
+ && isFinaleEntity(e.getEntity())) {
+ e.setCancelled(true);
+ }
+ }
+
+ private boolean isFinaleEntity(Entity entity) {
+ if (active.isEmpty()) {
+ return false;
+ }
+ UUID uuid = entity.getUniqueId();
+ if (byBoss.containsKey(uuid) || byMinion.containsKey(uuid)) {
+ return true;
+ }
+ return entity instanceof Projectile p && p.getShooter() instanceof Entity shooter
+ && (byBoss.containsKey(shooter.getUniqueId()) || byMinion.containsKey(shooter.getUniqueId()));
+ }
+
+ /**
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void onIslandDelete(IslandDeleteEvent e) {
+ Optional.ofNullable(active.get(e.getIsland().getUniqueId())).ifPresent(this::remove);
+ }
+
+ /**
+ * @param e - event
+ */
+ @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
+ public void onIslandReset(IslandResettedEvent e) {
+ Optional.ofNullable(active.get(e.getOldIsland().getUniqueId())).ifPresent(this::remove);
+ Optional.ofNullable(active.get(e.getIsland().getUniqueId())).ifPresent(this::remove);
+ }
+}
diff --git a/src/main/java/world/bentobox/aoneblock/listeners/GiantAttackGoal.java b/src/main/java/world/bentobox/aoneblock/listeners/GiantAttackGoal.java
new file mode 100644
index 00000000..922215d3
--- /dev/null
+++ b/src/main/java/world/bentobox/aoneblock/listeners/GiantAttackGoal.java
@@ -0,0 +1,89 @@
+package world.bentobox.aoneblock.listeners;
+
+import java.util.EnumSet;
+
+import org.bukkit.Bukkit;
+import org.bukkit.GameMode;
+import org.bukkit.NamespacedKey;
+import org.bukkit.entity.Giant;
+import org.bukkit.entity.LivingEntity;
+import org.bukkit.entity.Player;
+import org.bukkit.plugin.Plugin;
+import org.eclipse.jdt.annotation.NonNull;
+
+import com.destroystokyo.paper.entity.ai.Goal;
+import com.destroystokyo.paper.entity.ai.GoalKey;
+import com.destroystokyo.paper.entity.ai.GoalType;
+
+/**
+ * Giants have no AI in vanilla. This Paper mob goal makes one chase and hit
+ * the nearest survival player. Kept in its own class so servers without the
+ * Paper goal API only fail to load this, not the finale listener.
+ * @author tastybento
+ */
+public class GiantAttackGoal implements Goal {
+
+ private static final double RANGE = 32;
+ private static final int ATTACK_COOLDOWN = 20;
+
+ private final GoalKey key;
+ private final Giant giant;
+ private int cooldown;
+
+ GiantAttackGoal(Plugin plugin, Giant giant) {
+ this.key = GoalKey.of(Giant.class, new NamespacedKey(plugin, "giant_attack"));
+ this.giant = giant;
+ }
+
+ /**
+ * Give this giant the attack goal.
+ * @param plugin - owning plugin
+ * @param giant - giant
+ */
+ static void apply(Plugin plugin, Giant giant) {
+ Bukkit.getMobGoals().addGoal(giant, 1, new GiantAttackGoal(plugin, giant));
+ }
+
+ @Override
+ public boolean shouldActivate() {
+ LivingEntity target = giant.getTarget();
+ if (target == null || !target.isValid() || !isFair(target)) {
+ giant.setTarget(giant.getNearbyEntities(RANGE, RANGE, RANGE).stream()
+ .filter(GiantAttackGoal::isFair).map(LivingEntity.class::cast).findFirst().orElse(null));
+ }
+ return giant.getTarget() != null;
+ }
+
+ private static boolean isFair(Object e) {
+ return e instanceof Player p && !p.isDead()
+ && (p.getGameMode() == GameMode.SURVIVAL || p.getGameMode() == GameMode.ADVENTURE);
+ }
+
+ @Override
+ public void tick() {
+ LivingEntity target = giant.getTarget();
+ if (target == null) {
+ return;
+ }
+ giant.lookAt(target);
+ giant.getPathfinder().moveTo(target, 1.0);
+ // Vanilla reach scales awkwardly with a giant's hitbox, so use a manual check
+ double scale = Math.max(1D, giant.getWidth() / 3.6D);
+ double reach = 6D * scale;
+ if (--cooldown <= 0 && giant.getLocation().distanceSquared(target.getLocation()) < reach * reach) {
+ giant.swingMainHand();
+ giant.attack(target);
+ cooldown = ATTACK_COOLDOWN;
+ }
+ }
+
+ @Override
+ public @NonNull GoalKey getKey() {
+ return key;
+ }
+
+ @Override
+ public @NonNull EnumSet getTypes() {
+ return EnumSet.of(GoalType.MOVE, GoalType.LOOK, GoalType.TARGET);
+ }
+}
diff --git a/src/main/java/world/bentobox/aoneblock/listeners/WarningSounder.java b/src/main/java/world/bentobox/aoneblock/listeners/WarningSounder.java
index b7b03e5d..b654bacf 100644
--- a/src/main/java/world/bentobox/aoneblock/listeners/WarningSounder.java
+++ b/src/main/java/world/bentobox/aoneblock/listeners/WarningSounder.java
@@ -16,6 +16,7 @@
import world.bentobox.aoneblock.AOneBlock;
import world.bentobox.aoneblock.dataobjects.OneBlockIslands;
import world.bentobox.aoneblock.oneblocks.MobAspects;
+import world.bentobox.aoneblock.oneblocks.PhaseFinale;
/**
* Plays a warning sound
@@ -49,6 +50,33 @@ void play(@NonNull OneBlockIslands is, @NonNull Block block) {
}
+ /**
+ * Forewarns of the phase's boss over the last blocks of the phase: a heartbeat
+ * that rises in pitch as the end nears, and a bell toll just before it.
+ *
+ * @param block - the magic block
+ * @param finale - the phase's finale
+ * @param toGo - blocks left in the phase
+ */
+ void omen(@NonNull Block block, @NonNull PhaseFinale finale, int toGo) {
+ int warning = finale.warning();
+ if (toGo < 1 || toGo > warning) {
+ return;
+ }
+ float nearness = 1F - (float) toGo / warning;
+ block.getWorld().playSound(block.getLocation(), Sound.ENTITY_WARDEN_HEARTBEAT, 2F, 0.5F + 1.5F * nearness);
+ block.getWorld().spawnParticle(Particle.DUST, block.getLocation().add(new Vector(0.5, 1.0, 0.5)),
+ 5 + Math.round(20 * nearness), 0.5, 0.2, 0.5, 1, new Particle.DustOptions(Color.fromRGB(120, 0, 0), 1.5F));
+ if (toGo == Math.min(BELL_AT, warning)) {
+ block.getWorld().playSound(block.getLocation(), Sound.BLOCK_BELL_RESONATE, 2F, 0.8F);
+ }
+ }
+
+ /**
+ * Blocks before the end of the phase at which the bell tolls.
+ */
+ static final int BELL_AT = 5;
+
private void initialize() {
Map m = new EnumMap<>(EntityType.class);
m.put(EntityType.BLAZE, new MobAspects(Sound.ENTITY_BLAZE_AMBIENT, Color.fromRGB(238, 211, 91)));
diff --git a/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlockPhase.java b/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlockPhase.java
index 1f45e909..a111e9c1 100644
--- a/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlockPhase.java
+++ b/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlockPhase.java
@@ -58,6 +58,7 @@ public class OneBlockPhase {
private List endCommands;
private List firstTimeEndCommands;
private List requirements;
+ private PhaseFinale finale;
private Map fixedBlocks;
private Map holograms;
@@ -429,6 +430,20 @@ public void setRequirements(List requirements) {
this.requirements = requirements;
}
+ /**
+ * @return the boss finale that ends this phase, or null if there is none
+ */
+ public PhaseFinale getFinale() {
+ return finale;
+ }
+
+ /**
+ * @param finale the boss finale that ends this phase, or null for none
+ */
+ public void setFinale(PhaseFinale finale) {
+ this.finale = finale;
+ }
+
/**
* @return the endCommands
*/
diff --git a/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlocksManager.java b/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlocksManager.java
index b0e9f17d..8f8441c6 100644
--- a/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlocksManager.java
+++ b/src/main/java/world/bentobox/aoneblock/oneblocks/OneBlocksManager.java
@@ -14,6 +14,7 @@
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
+import java.util.EnumMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
@@ -88,6 +89,8 @@ public class OneBlocksManager {
private static final String END_COMMANDS = "end-commands";
private static final String END_COMMANDS_FIRST_TIME = "end-commands-first-time";
private static final String REQUIREMENTS = "requirements";
+ private static final String FINALE = "finale";
+ private static final String FINALE_LOG_PREFIX = "Phase ";
private static final String REQUIRED_MC_VERSION = "requiredMinecraftVersion";
// Possessive quantifiers - version strings need no backtracking and this
// keeps pathological inputs from recursing deeply in the regex engine
@@ -1129,6 +1132,88 @@ void parsePhaseSection(OneBlockPhase obPhase, ConfigurationSection phaseConfig,
addCommands(obPhase, phaseConfig);
// Requirements
addRequirements(obPhase, phaseConfig);
+ // Finale
+ addFinale(obPhase, phaseConfig);
+ }
+
+ /**
+ * Reads the optional finale section, the boss that ends the phase.
+ *
+ * @param obPhase phase to fill
+ * @param phase configuration section being read
+ */
+ void addFinale(OneBlockPhase obPhase, ConfigurationSection phase) {
+ ConfigurationSection sec = phase.getConfigurationSection(FINALE);
+ if (sec == null) {
+ return;
+ }
+ String phaseName = obPhase.getPhaseName();
+ EntityType boss = Enums.getIfPresent(EntityType.class, sec.getString("boss", "").toUpperCase(Locale.ENGLISH))
+ .orNull();
+ if (boss == null || !boss.isAlive() || !boss.isSpawnable()) {
+ addon.logWarning(FINALE_LOG_PREFIX + phaseName + " finale: boss '" + sec.getString("boss")
+ + "' is not a living entity type on this server. The finale is disabled.");
+ return;
+ }
+ Map minions = readFinaleMinions(sec.getConfigurationSection("minions"), phaseName);
+ Map drops = readFinaleDrops(sec.getConfigurationSection("drops"), phaseName);
+ obPhase.setFinale(new PhaseFinale(boss, sec.getString(NAME, Util.prettifyText(boss.name())),
+ Math.max(1D, sec.getDouble("health", 100D)), Math.max(0.1D, sec.getDouble("scale", 1D)),
+ sec.getDouble("damage", 0D), sec.getDouble("speed", 0D), sec.getBoolean("void-respawn", true),
+ Math.max(0, sec.getInt("warning", PhaseFinale.DEFAULT_WARNING)), minions, drops,
+ sec.getStringList("commands"), sec.getStringList("first-time-commands")));
+ }
+
+ private Map readFinaleMinions(ConfigurationSection minionSec, String phaseName) {
+ Map minions = new EnumMap<>(EntityType.class);
+ if (minionSec == null) {
+ return minions;
+ }
+ for (String key : minionSec.getKeys(false)) {
+ EntityType et = Enums.getIfPresent(EntityType.class, key.toUpperCase(Locale.ENGLISH)).orNull();
+ if (et == null || !et.isAlive() || !et.isSpawnable()) {
+ addon.logWarning(FINALE_LOG_PREFIX + phaseName + " finale: skipping unknown minion " + key);
+ } else {
+ minions.put(et, Math.max(0, minionSec.getInt(key)));
+ }
+ }
+ return minions;
+ }
+
+ private Map readFinaleDrops(ConfigurationSection dropSec, String phaseName) {
+ Map drops = new EnumMap<>(Material.class);
+ if (dropSec == null) {
+ return drops;
+ }
+ for (String key : dropSec.getKeys(false)) {
+ Material m = Material.matchMaterial(key);
+ if (m == null || !m.isItem()) {
+ addon.logWarning(FINALE_LOG_PREFIX + phaseName + " finale: skipping unknown drop " + key);
+ } else {
+ drops.put(m, Math.max(1, dropSec.getInt(key)));
+ }
+ }
+ return drops;
+ }
+
+ private void saveFinale(ConfigurationSection phSec, OneBlockPhase p) {
+ PhaseFinale f = p.getFinale();
+ if (f == null) {
+ return;
+ }
+ ConfigurationSection sec = phSec.createSection(FINALE);
+ sec.set("boss", f.boss().name());
+ sec.set(NAME, f.name());
+ sec.set("health", f.health());
+ sec.set("scale", f.scale());
+ sec.set("damage", f.damage());
+ sec.set("speed", f.speed());
+ sec.set("void-respawn", f.voidRespawn());
+ sec.set("warning", f.warning());
+ f.minions().forEach((k, v) -> sec.set("minions." + k.name(), v));
+ f.drops().forEach((k, v) -> sec.set("drops." + k.name(), v));
+ sec.set("commands", f.commands());
+ sec.set("first-time-commands", f.firstTimeCommands());
}
/**
@@ -1692,6 +1777,7 @@ private boolean saveMainPhase(OneBlockPhase p) {
saveEntities(phSec, p);
saveHolos(phSec, p);
saveCommands(phSec, p);
+ saveFinale(phSec, p);
}
try {
// Save
diff --git a/src/main/java/world/bentobox/aoneblock/oneblocks/PhaseFinale.java b/src/main/java/world/bentobox/aoneblock/oneblocks/PhaseFinale.java
new file mode 100644
index 00000000..6ad574a7
--- /dev/null
+++ b/src/main/java/world/bentobox/aoneblock/oneblocks/PhaseFinale.java
@@ -0,0 +1,46 @@
+package world.bentobox.aoneblock.oneblocks;
+
+import java.util.List;
+import java.util.Map;
+
+import org.bukkit.Material;
+import org.bukkit.entity.EntityType;
+
+/**
+ * The boss encounter that ends a phase. Defined by the optional {@code finale:}
+ * section of a phase file.
+ *
+ * @param boss entity type of the boss
+ * @param name display name of the boss, MiniMessage or legacy codes
+ * @param health base maximum health, before scaling for players
+ * @param scale size multiplier, 1 is normal size
+ * @param damage attack damage, or 0 or less to keep the mob's default
+ * @param speed movement speed, or 0 or less to keep the mob's default
+ * @param voidRespawn if true a boss that falls into the void returns to the
+ * magic block; if false the fall kills it and counts as a win
+ * @param warning how many blocks before the end of the phase the omen starts
+ * @param minions mobs that spawn alongside the boss, and how many of each
+ * @param drops items dropped at the magic block when the boss is defeated
+ * @param commands commands run every time the boss is defeated
+ * @param firstTimeCommands commands run only the first time the island defeats this boss
+ * @author tastybento
+ */
+public record PhaseFinale(EntityType boss, String name, double health, double scale, double damage, double speed,
+ boolean voidRespawn, int warning, Map minions, Map drops,
+ List commands, List firstTimeCommands) {
+
+ /**
+ * Default number of blocks of forewarning.
+ */
+ public static final int DEFAULT_WARNING = 20;
+
+ /**
+ * Defensive copies so the record is immutable.
+ */
+ public PhaseFinale {
+ minions = Map.copyOf(minions);
+ drops = Map.copyOf(drops);
+ commands = List.copyOf(commands);
+ firstTimeCommands = List.copyOf(firstTimeCommands);
+ }
+}
diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml
index 4fffa1d0..d3688154 100644
--- a/src/main/resources/config.yml
+++ b/src/main/resources/config.yml
@@ -398,6 +398,10 @@ island:
# Drop broken blocks on top of magic block
# If you want Jobs or other plugins to recognize magic block breaking this must be false
drop-on-top: true
+ # Phase finales
+ # A phase whose file has a finale section ends with a boss that must be defeated
+ # before the magic block moves on to the next phase. Set to false to turn all finales off.
+ phase-finales: true
# Magic block mob warning
# Players might be able to hear hostile mobs up to this many blocks away
# Minimum is 0 (no warning), max is 5
diff --git a/src/main/resources/locales/en-US.yml b/src/main/resources/locales/en-US.yml
index 287fd963..818446c2 100755
--- a/src/main/resources/locales/en-US.yml
+++ b/src/main/resources/locales/en-US.yml
@@ -130,6 +130,12 @@ aoneblock:
insufficient-bank-balance: "The island bank balance is too low to proceed! It must be [number]."
insufficient-permission: "You can proceed no further until you obtain the [name] permission!"
cooldown: "Next phase will be available in [number] seconds!"
+ finale:
+ start: "[name] rises from the magic block! Defeat it to move on."
+ defeat-boss: "The magic block is sealed until [name] is defeated!"
+ defeated: "[name] has been defeated! The magic block is yours again."
+ pending: "Phase boss: [name] - hit the magic block to face it"
+ retreat: "[name] has retreated. Hit the magic block when you are ready to face it again."
placeholders:
infinite: Infinite
my-island-phase-default: Unknown
diff --git a/src/main/resources/phases/0_plains.yml b/src/main/resources/phases/0_plains.yml
index afda8826..90f64d77 100644
--- a/src/main/resources/phases/0_plains.yml
+++ b/src/main/resources/phases/0_plains.yml
@@ -339,3 +339,50 @@
PIG: 150
VILLAGER: 15
CHICKEN: 200
+
+ # -------------------------------------------------------------------------
+ # finale - the boss that ends the phase (optional)
+ # -------------------------------------------------------------------------
+ # When the last block of the phase is mined the magic block is sealed and
+ # the boss spawns on top of it. The phase does not change until it is dead.
+ # Only damage from players (melee, projectiles, pets) hurts the boss, and it
+ # cannot change blocks. If everyone dies or leaves, the boss retreats and
+ # hitting the magic block summons it again. Each lost fight makes the next
+ # attempt 10% easier, down to half health. Boss health grows by 50% for each
+ # extra player on the island, up to 4 players.
+ #
+ # The last blocks of the phase are forewarned by a heartbeat that rises in
+ # pitch, then a bell toll five blocks from the end.
+ #
+ # boss - EntityType of the boss. GIANT has no AI in vanilla;
+ # it is given one here (needs Paper).
+ # name - display name, MiniMessage or legacy & codes.
+ # health - base max health. Server max is 1024 unless raised in
+ # spigot.yml (settings.attribute.maxHealth).
+ # scale - size multiplier. 1 is normal. Default 1.
+ # damage - attack damage. Omit or 0 for the mob's default.
+ # speed - movement speed. Omit or 0 for the mob's default.
+ # void-respawn - true (default): a boss knocked into the void comes
+ # back to the magic block. false: the void kills it
+ # and that counts as a win.
+ # warning - how many blocks before the end the omen starts.
+ # Default 20. 0 for no warning.
+ # minions - mobs that spawn with the boss, TYPE: count.
+ # drops - items dropped when the boss dies, MATERIAL: amount.
+ # commands - run every time the boss is defeated. Same prefixes
+ # and placeholders as end-commands.
+ # first-time-commands - run only the first time the island defeats it.
+ #
+ # Turn all finales off with island.phase-finales in config.yml.
+ finale:
+ boss: GIANT
+ name: 'The Colossus'
+ health: 100
+ scale: 0.5
+ damage: 4
+ speed: 0.25
+ minions:
+ ZOMBIE: 2
+ drops:
+ IRON_INGOT: 8
+ BREAD: 8
diff --git a/src/main/resources/phases/10500_deep_dark.yml b/src/main/resources/phases/10500_deep_dark.yml
index 9bb8e6f5..55fc621c 100644
--- a/src/main/resources/phases/10500_deep_dark.yml
+++ b/src/main/resources/phases/10500_deep_dark.yml
@@ -40,3 +40,10 @@
holograms: {}
start-commands: []
end-commands: []
+ finale:
+ boss: WARDEN
+ name: 'The Warden'
+ health: 300
+ drops:
+ DIAMOND: 12
+ ECHO_SHARD: 8
diff --git a/src/main/resources/phases/11500_the end.yml b/src/main/resources/phases/11500_the end.yml
index dd22ecee..3cb93dc3 100644
--- a/src/main/resources/phases/11500_the end.yml
+++ b/src/main/resources/phases/11500_the end.yml
@@ -14,3 +14,14 @@
mobs:
SHULKER: 80
ENDERMAN: 500
+ finale:
+ boss: ENDERMAN
+ name: 'The Void Walker'
+ health: 320
+ scale: 2.5
+ damage: 12
+ minions:
+ ENDERMITE: 5
+ drops:
+ DIAMOND: 12
+ ENDER_PEARL: 16
diff --git a/src/main/resources/phases/12000_lush_caves.yml b/src/main/resources/phases/12000_lush_caves.yml
index 82e74902..426be32b 100644
--- a/src/main/resources/phases/12000_lush_caves.yml
+++ b/src/main/resources/phases/12000_lush_caves.yml
@@ -41,3 +41,13 @@
'0': '&aWelcome to the Lush Caves!'
start-commands: []
end-commands: []
+ finale:
+ boss: BOGGED
+ name: 'The Mossback'
+ health: 320
+ scale: 2
+ minions:
+ BOGGED: 3
+ drops:
+ DIAMOND: 12
+ GOLDEN_APPLE: 4
diff --git a/src/main/resources/phases/12500_dripstone_caves.yml b/src/main/resources/phases/12500_dripstone_caves.yml
index 9af88e8b..a45ccf7f 100644
--- a/src/main/resources/phases/12500_dripstone_caves.yml
+++ b/src/main/resources/phases/12500_dripstone_caves.yml
@@ -38,3 +38,14 @@
'0': '&bProceed with caution!'
start-commands: []
end-commands: []
+ finale:
+ boss: SILVERFISH
+ name: 'The Burrower'
+ health: 340
+ scale: 6
+ damage: 10
+ minions:
+ SILVERFISH: 6
+ drops:
+ DIAMOND: 14
+ ANCIENT_DEBRIS: 2
diff --git a/src/main/resources/phases/13000_mangrove_swamp.yml b/src/main/resources/phases/13000_mangrove_swamp.yml
index 7aaad451..52df3250 100644
--- a/src/main/resources/phases/13000_mangrove_swamp.yml
+++ b/src/main/resources/phases/13000_mangrove_swamp.yml
@@ -45,3 +45,14 @@
'0': '&2The waters here are murky...'
start-commands: []
end-commands: []
+ finale:
+ boss: CAVE_SPIDER
+ name: 'The Mire Lurker'
+ health: 340
+ scale: 4
+ damage: 10
+ minions:
+ CAVE_SPIDER: 4
+ drops:
+ DIAMOND: 14
+ EXPERIENCE_BOTTLE: 32
diff --git a/src/main/resources/phases/13500_meadow.yml b/src/main/resources/phases/13500_meadow.yml
index d8dfdc6e..d88260b7 100644
--- a/src/main/resources/phases/13500_meadow.yml
+++ b/src/main/resources/phases/13500_meadow.yml
@@ -52,3 +52,13 @@
'0': '&dA peaceful meadow!'
start-commands: []
end-commands: []
+ finale:
+ boss: EVOKER
+ name: 'The Summoner'
+ health: 360
+ scale: 1.5
+ minions:
+ VINDICATOR: 2
+ drops:
+ DIAMOND: 14
+ TOTEM_OF_UNDYING: 1
diff --git a/src/main/resources/phases/14000_cherry_grove.yml b/src/main/resources/phases/14000_cherry_grove.yml
index 0545c27e..6dac9fa9 100644
--- a/src/main/resources/phases/14000_cherry_grove.yml
+++ b/src/main/resources/phases/14000_cherry_grove.yml
@@ -40,3 +40,11 @@
'0': '&dBlossom in bloom!'
start-commands: []
end-commands: []
+ finale:
+ boss: ILLUSIONER
+ name: 'The Petal Phantom'
+ health: 360
+ scale: 1.3
+ drops:
+ DIAMOND: 16
+ ANCIENT_DEBRIS: 2
diff --git a/src/main/resources/phases/14500_jagged_peaks.yml b/src/main/resources/phases/14500_jagged_peaks.yml
index a8324eb3..047ca96d 100644
--- a/src/main/resources/phases/14500_jagged_peaks.yml
+++ b/src/main/resources/phases/14500_jagged_peaks.yml
@@ -44,3 +44,13 @@
'0': '&fHigh altitude ahead!'
start-commands: []
end-commands: []
+ finale:
+ boss: BREEZE
+ name: 'The Gale'
+ health: 380
+ scale: 2
+ minions:
+ STRAY: 3
+ drops:
+ DIAMOND: 16
+ ENCHANTED_GOLDEN_APPLE: 1
diff --git a/src/main/resources/phases/15000_sulfur_caves.yml b/src/main/resources/phases/15000_sulfur_caves.yml
index f7c86ceb..b0ac66bb 100644
--- a/src/main/resources/phases/15000_sulfur_caves.yml
+++ b/src/main/resources/phases/15000_sulfur_caves.yml
@@ -53,3 +53,13 @@
'0': '&eBeware the noxious fumes!'
start-commands: []
end-commands: []
+ finale:
+ boss: BLAZE
+ name: 'Brimstone'
+ health: 400
+ scale: 2
+ minions:
+ MAGMA_CUBE: 3
+ drops:
+ DIAMOND: 16
+ ANCIENT_DEBRIS: 3
diff --git a/src/main/resources/phases/15500_dappled_forest.yml b/src/main/resources/phases/15500_dappled_forest.yml
index e6a71c8b..2ef1d84d 100644
--- a/src/main/resources/phases/15500_dappled_forest.yml
+++ b/src/main/resources/phases/15500_dappled_forest.yml
@@ -65,3 +65,14 @@
'0': '&6Autumn has come to the forest!'
start-commands: []
end-commands: []
+ finale:
+ boss: VINDICATOR
+ name: 'The Woodcutter'
+ health: 400
+ scale: 1.8
+ damage: 14
+ minions:
+ VINDICATOR: 2
+ drops:
+ DIAMOND: 16
+ NETHERITE_INGOT: 1
diff --git a/src/main/resources/phases/2000_winter.yml b/src/main/resources/phases/2000_winter.yml
index 1fff3f3c..c9f00ab7 100644
--- a/src/main/resources/phases/2000_winter.yml
+++ b/src/main/resources/phases/2000_winter.yml
@@ -31,3 +31,13 @@
RABBIT: 50
CHICKEN: 10
GOAT: 10
+ finale:
+ boss: STRAY
+ name: 'The Frostbitten'
+ health: 140
+ scale: 2
+ minions:
+ STRAY: 3
+ drops:
+ DIAMOND: 3
+ PACKED_ICE: 16
diff --git a/src/main/resources/phases/3000_ocean.yml b/src/main/resources/phases/3000_ocean.yml
index 4765d525..2dae3551 100644
--- a/src/main/resources/phases/3000_ocean.yml
+++ b/src/main/resources/phases/3000_ocean.yml
@@ -39,3 +39,14 @@
DROWNED: 600
FROG: 10
+ finale:
+ boss: DROWNED
+ name: 'The Drowned King'
+ health: 160
+ scale: 2.5
+ damage: 7
+ minions:
+ DROWNED: 4
+ drops:
+ DIAMOND: 4
+ HEART_OF_THE_SEA: 1
diff --git a/src/main/resources/phases/4000_jungle.yml b/src/main/resources/phases/4000_jungle.yml
index 0584dd65..b932f1cc 100644
--- a/src/main/resources/phases/4000_jungle.yml
+++ b/src/main/resources/phases/4000_jungle.yml
@@ -34,3 +34,11 @@
PANDA: 5
CHICKEN: 20
FROG: 5
+ finale:
+ boss: IRON_GOLEM
+ name: 'The Temple Guardian'
+ health: 180
+ scale: 1.5
+ drops:
+ DIAMOND: 5
+ EMERALD: 8
diff --git a/src/main/resources/phases/5000_swamp.yml b/src/main/resources/phases/5000_swamp.yml
index de6f3bca..c160181d 100644
--- a/src/main/resources/phases/5000_swamp.yml
+++ b/src/main/resources/phases/5000_swamp.yml
@@ -30,3 +30,13 @@
CHICKEN: 20
TADPOLE: 20
FROG: 40
+ finale:
+ boss: WITCH
+ name: 'The Bog Witch'
+ health: 180
+ scale: 1.5
+ minions:
+ SLIME: 3
+ drops:
+ DIAMOND: 5
+ EXPERIENCE_BOTTLE: 16
diff --git a/src/main/resources/phases/6000_dungeon.yml b/src/main/resources/phases/6000_dungeon.yml
index f3c7ad0c..8184f2c1 100644
--- a/src/main/resources/phases/6000_dungeon.yml
+++ b/src/main/resources/phases/6000_dungeon.yml
@@ -41,3 +41,15 @@
BAT: 3
AXOLOTL: 1
GLOW_SQUID: 1
+ finale:
+ boss: WITHER_SKELETON
+ name: 'The Jailer'
+ health: 200
+ scale: 1.5
+ damage: 9
+ minions:
+ SKELETON: 3
+ ZOMBIE: 3
+ drops:
+ DIAMOND: 6
+ GOLDEN_APPLE: 2
diff --git a/src/main/resources/phases/7000_desert.yml b/src/main/resources/phases/7000_desert.yml
index a94765e1..8597fb98 100644
--- a/src/main/resources/phases/7000_desert.yml
+++ b/src/main/resources/phases/7000_desert.yml
@@ -18,3 +18,14 @@
CREEPER: 10
ENDERMAN: 10
RABBIT: 50
+ finale:
+ boss: HUSK
+ name: 'The Pharaoh'
+ health: 220
+ scale: 3
+ damage: 9
+ minions:
+ HUSK: 4
+ drops:
+ DIAMOND: 6
+ GOLD_BLOCK: 4
diff --git a/src/main/resources/phases/700_underground.yml b/src/main/resources/phases/700_underground.yml
index e4d8214f..0f1b233c 100644
--- a/src/main/resources/phases/700_underground.yml
+++ b/src/main/resources/phases/700_underground.yml
@@ -42,3 +42,14 @@
BAT: 30
AXOLOTL: 1
GLOW_SQUID: 1
+ finale:
+ boss: SPIDER
+ name: 'The Broodmother'
+ health: 120
+ scale: 3
+ damage: 5
+ minions:
+ CAVE_SPIDER: 4
+ drops:
+ IRON_INGOT: 12
+ DIAMOND: 2
diff --git a/src/main/resources/phases/7500_the nether.yml b/src/main/resources/phases/7500_the nether.yml
index 794f8b57..0f32655d 100644
--- a/src/main/resources/phases/7500_the nether.yml
+++ b/src/main/resources/phases/7500_the nether.yml
@@ -40,3 +40,13 @@
ENDERMAN: 20
BLAZE: 200
WITHER_SKELETON: 20
+ finale:
+ boss: PIGLIN_BRUTE
+ name: 'The Warlord'
+ health: 240
+ scale: 2
+ minions:
+ WITHER_SKELETON: 3
+ drops:
+ DIAMOND: 8
+ ANCIENT_DEBRIS: 1
diff --git a/src/main/resources/phases/8500_plenty.yml b/src/main/resources/phases/8500_plenty.yml
index 0615f37b..ea757e9e 100644
--- a/src/main/resources/phases/8500_plenty.yml
+++ b/src/main/resources/phases/8500_plenty.yml
@@ -63,3 +63,13 @@
CHICKEN: 1
ALLAY: 1
+ finale:
+ boss: RAVAGER
+ name: 'The Harvest Beast'
+ health: 260
+ scale: 1.3
+ minions:
+ PILLAGER: 3
+ drops:
+ DIAMOND: 8
+ GOLDEN_APPLE: 4
diff --git a/src/main/resources/phases/9500_desolation.yml b/src/main/resources/phases/9500_desolation.yml
index 1ed76089..a320aa93 100644
--- a/src/main/resources/phases/9500_desolation.yml
+++ b/src/main/resources/phases/9500_desolation.yml
@@ -50,3 +50,14 @@
EVOKER: 5
ENDERMITE: 10
WITHER_SKELETON: 5
+ finale:
+ boss: GIANT
+ name: 'The Last Titan'
+ health: 300
+ damage: 10
+ speed: 0.3
+ minions:
+ ZOMBIE: 6
+ drops:
+ DIAMOND: 10
+ ANCIENT_DEBRIS: 2
diff --git a/src/test/java/world/bentobox/aoneblock/commands/island/IslandSetCountCommandTest.java b/src/test/java/world/bentobox/aoneblock/commands/island/IslandSetCountCommandTest.java
index 949c1962..ccc21597 100644
--- a/src/test/java/world/bentobox/aoneblock/commands/island/IslandSetCountCommandTest.java
+++ b/src/test/java/world/bentobox/aoneblock/commands/island/IslandSetCountCommandTest.java
@@ -27,6 +27,7 @@
import org.mockito.MockedStatic;
import org.mockito.Mockito;
+import world.bentobox.aoneblock.listeners.FinaleListener;
import world.bentobox.aoneblock.AOneBlock;
import world.bentobox.aoneblock.CommonTestSetup;
import world.bentobox.aoneblock.Settings;
@@ -127,6 +128,8 @@ public void setUp() throws Exception {
// BlockListener
when(addon.getBlockListener()).thenReturn(bl);
+ FinaleListener finaleListener = mock(FinaleListener.class);
+ when(addon.getFinaleListener()).thenReturn(finaleListener);
when(bl.getIsland(island)).thenReturn(oneBlockIsland);
// DUT
diff --git a/src/test/java/world/bentobox/aoneblock/listeners/BossBarListenerTest.java b/src/test/java/world/bentobox/aoneblock/listeners/BossBarListenerTest.java
index 69872f46..d6009ade 100644
--- a/src/test/java/world/bentobox/aoneblock/listeners/BossBarListenerTest.java
+++ b/src/test/java/world/bentobox/aoneblock/listeners/BossBarListenerTest.java
@@ -8,6 +8,7 @@
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -26,6 +27,11 @@
import net.kyori.adventure.text.format.TextColor;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
+import world.bentobox.aoneblock.events.PhaseFinaleEndEvent;
+import world.bentobox.aoneblock.events.PhaseFinaleStartEvent;
+import world.bentobox.bentobox.util.Util;
+import world.bentobox.aoneblock.oneblocks.PhaseFinale;
+import world.bentobox.aoneblock.oneblocks.OneBlockPhase;
import world.bentobox.aoneblock.AOneBlock;
import world.bentobox.aoneblock.CommonTestSetup;
import world.bentobox.aoneblock.Settings;
@@ -224,4 +230,47 @@ void testNullPlayerUUIDDoesNotThrow() {
verify(mockPlayer, never()).sendActionBar(any(Component.class));
verify(bossBar, never()).addPlayer(any());
}
+
+ /**
+ * While a phase boss is still to be defeated the bar names the boss instead of
+ * showing the next phase's progress.
+ */
+ @Test
+ void testBossBarShowsPendingBoss() {
+ OneBlockPhase phase = new OneBlockPhase("0");
+ phase.setFinale(new PhaseFinale(org.bukkit.entity.EntityType.ZOMBIE, "Colossus", 100, 1,
+ 0, 0, true, 20, java.util.Map.of(), java.util.Map.of(), java.util.List.of(), java.util.List.of()));
+ when(obi.getFinalePending()).thenReturn("Plains");
+ when(obm.getPhase("Plains")).thenReturn(java.util.Optional.of(phase));
+ mockedUtil.when(() -> Util.parseMiniMessageOrLegacy(anyString()))
+ .thenAnswer(a -> Component.text(a.getArgument(0, String.class)));
+ when(island.isAllowed(addon.ONEBLOCK_BOSSBAR)).thenReturn(true);
+ fireMagicBlockEvent();
+ verify(bossBar).setProgress(1D);
+ verify(bossBar, never()).setProgress(0.8D);
+ verify(bossBar).addPlayer(mockPlayer);
+ }
+
+ /**
+ * The phase bar steps aside when the boss spawns and comes straight back when
+ * the fight ends, without waiting for the next block break.
+ */
+ @Test
+ void testBossBarRefreshedAroundFinale() {
+ when(island.isAllowed(addon.ONEBLOCK_BOSSBAR)).thenReturn(true);
+ when(island.getWorld()).thenReturn(world);
+ when(island.onIsland(any())).thenReturn(true);
+ when(world.getPlayers()).thenReturn(java.util.List.of(mockPlayer));
+ when(mockPlayer.getUniqueId()).thenReturn(uuid);
+ fireMagicBlockEvent();
+ verify(bossBar, times(1)).addPlayer(mockPlayer);
+
+ PhaseFinale finale = new PhaseFinale(org.bukkit.entity.EntityType.ZOMBIE, "Colossus", 100, 1, 0, 0, true, 20,
+ java.util.Map.of(), java.util.Map.of(), java.util.List.of(), java.util.List.of());
+ bbl.onFinaleStart(new PhaseFinaleStartEvent(island, uuid, block, "Plains", finale));
+ verify(bossBar).removeAll();
+
+ bbl.onFinaleEnd(new PhaseFinaleEndEvent(island, uuid, block, "Plains", true, true));
+ verify(bossBar, times(2)).addPlayer(mockPlayer);
+ }
}
diff --git a/src/test/java/world/bentobox/aoneblock/listeners/FinaleListenerTest.java b/src/test/java/world/bentobox/aoneblock/listeners/FinaleListenerTest.java
new file mode 100644
index 00000000..01e9c16c
--- /dev/null
+++ b/src/test/java/world/bentobox/aoneblock/listeners/FinaleListenerTest.java
@@ -0,0 +1,443 @@
+package world.bentobox.aoneblock.listeners;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.UUID;
+
+import org.bukkit.Bukkit;
+import org.bukkit.Difficulty;
+import org.bukkit.GameMode;
+import org.bukkit.Location;
+import org.bukkit.Material;
+import org.bukkit.attribute.Attribute;
+import org.bukkit.attribute.AttributeInstance;
+import org.bukkit.block.Block;
+import org.bukkit.entity.Arrow;
+import org.bukkit.entity.EntityType;
+import org.bukkit.entity.Item;
+import org.bukkit.entity.Zombie;
+import org.bukkit.event.entity.EntityChangeBlockEvent;
+import org.bukkit.event.entity.EntityDamageByEntityEvent;
+import org.bukkit.event.entity.EntityDamageEvent;
+import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
+import org.bukkit.event.entity.EntityDeathEvent;
+import org.bukkit.event.entity.PlayerDeathEvent;
+import org.bukkit.inventory.ItemStack;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mock;
+
+import net.kyori.adventure.text.Component;
+import world.bentobox.aoneblock.AOneBlock;
+import world.bentobox.aoneblock.CommonTestSetup;
+import world.bentobox.aoneblock.Settings;
+import world.bentobox.aoneblock.dataobjects.OneBlockIslands;
+import world.bentobox.aoneblock.events.PhaseFinaleEndEvent;
+import world.bentobox.aoneblock.events.PhaseFinaleStartEvent;
+import world.bentobox.aoneblock.oneblocks.OneBlockPhase;
+import world.bentobox.aoneblock.oneblocks.OneBlocksManager;
+import world.bentobox.aoneblock.oneblocks.PhaseFinale;
+import world.bentobox.bentobox.api.user.User;
+import world.bentobox.bentobox.managers.PlayersManager;
+import world.bentobox.bentobox.util.Util;
+
+/**
+ * Tests the phase finale boss fights.
+ */
+class FinaleListenerTest extends CommonTestSetup {
+
+ private static final String PLAINS = "Plains";
+
+ @Mock
+ private AOneBlock addon;
+ @Mock
+ private OneBlocksManager obm;
+ @Mock
+ private BlockListener blis;
+ @Mock
+ private CheckPhase check;
+ @Mock
+ private Block block;
+ @Mock
+ private Zombie boss;
+ @Mock
+ private AttributeInstance attribute;
+ @Mock
+ private PlayersManager pm;
+
+ private Settings settings;
+ private OneBlockPhase plains;
+ private OneBlockPhase next;
+ private OneBlockIslands is;
+ private FinaleListener fl;
+ private UUID bossId;
+
+ @Override
+ @BeforeEach
+ public void setUp() throws Exception {
+ super.setUp();
+ settings = new Settings();
+ settings.setClearBlocks(false);
+ when(addon.getSettings()).thenReturn(settings);
+ when(addon.getPlugin()).thenReturn(plugin);
+ when(addon.getOneBlockManager()).thenReturn(obm);
+ when(addon.getBlockListener()).thenReturn(blis);
+ when(addon.getPlayers()).thenReturn(pm);
+ when(blis.getCheckPhase()).thenReturn(check);
+ mockedUtil.when(() -> Util.parseMiniMessageOrLegacy(anyString()))
+ .thenAnswer(a -> Component.text(a.getArgument(0, String.class)));
+
+ // Phases
+ plains = new OneBlockPhase("0");
+ plains.setPhaseName(PLAINS);
+ plains.setFinale(finale(true));
+ next = new OneBlockPhase("700");
+ next.setPhaseName("Underground");
+ when(obm.getPhase(PLAINS)).thenReturn(Optional.of(plains));
+
+ // Island
+ when(island.getUniqueId()).thenReturn("island-id");
+ when(island.onIsland(any())).thenReturn(true);
+ when(island.getOwner()).thenReturn(uuid);
+ is = new OneBlockIslands("island-id");
+ is.setPhaseName(PLAINS);
+
+ // World
+ when(world.getDifficulty()).thenReturn(Difficulty.NORMAL);
+ when(world.getPlayers()).thenReturn(List.of(mockPlayer));
+ when(world.getMinHeight()).thenReturn(-64);
+ Item dropped = mock(Item.class);
+ when(world.dropItem(any(), any())).thenReturn(dropped);
+ when(block.getWorld()).thenReturn(world);
+ when(block.getLocation()).thenAnswer(a -> new Location(world, 0, 64, 0));
+
+ // Player
+ when(mockPlayer.getGameMode()).thenReturn(GameMode.SURVIVAL);
+ when(mockPlayer.getLocation()).thenReturn(new Location(world, 1, 65, 1));
+ when(mockPlayer.getWorld()).thenReturn(world);
+ mockedBukkit.when(() -> Bukkit.getPlayer(any(UUID.class))).thenReturn(mockPlayer);
+ User.setPlugin(plugin);
+ User user = User.getInstance(mockPlayer);
+ when(pm.getUser(any(UUID.class))).thenReturn(user);
+
+ // Boss
+ bossId = UUID.randomUUID();
+ when(boss.getUniqueId()).thenReturn(bossId);
+ when(boss.isValid()).thenReturn(true);
+ when(boss.getType()).thenReturn(EntityType.ZOMBIE);
+ when(boss.getAttribute(any())).thenReturn(attribute);
+ when(boss.getLocation()).thenReturn(new Location(world, 0, 65, 0));
+ when(boss.getWorld()).thenReturn(world);
+ when(boss.getBoundingBox()).thenReturn(new org.bukkit.util.BoundingBox(0, 65, 0, 1, 67, 1));
+ when(boss.getKiller()).thenReturn(mockPlayer);
+ when(attribute.getValue()).thenReturn(100D);
+ when(world.spawnEntity(any(), eq(EntityType.ZOMBIE))).thenReturn(boss);
+
+ fl = new FinaleListener(addon);
+ }
+
+ @Override
+ @AfterEach
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ private PhaseFinale finale(boolean voidRespawn) {
+ return new PhaseFinale(EntityType.ZOMBIE, "The Colossus", 100, 2, 4, 0, voidRespawn, 20, Map.of(),
+ Map.of(Material.IRON_INGOT, 8), List.of(), List.of());
+ }
+
+ private void summon() {
+ is.setFinalePending(PLAINS);
+ assertTrue(fl.gate(island, is, mockPlayer, block));
+ }
+
+ @Test
+ void testScaledHealth() {
+ assertEquals(100D, FinaleListener.scaledHealth(100, 1, 0));
+ assertEquals(100D, FinaleListener.scaledHealth(100, 0, 0));
+ assertEquals(150D, FinaleListener.scaledHealth(100, 2, 0));
+ // Capped at four players
+ assertEquals(250D, FinaleListener.scaledHealth(100, 9, 0));
+ // Mercy
+ assertEquals(90D, FinaleListener.scaledHealth(100, 1, 1), 0.001);
+ assertEquals(50D, FinaleListener.scaledHealth(100, 1, 20), 0.001);
+ }
+
+ @Test
+ void testArmOnLastBlock() {
+ when(obm.getPhase(700)).thenReturn(next);
+ is.setBlockNumber(700);
+ fl.arm(is, plains);
+ assertEquals(PLAINS, is.getFinalePending());
+ }
+
+ @Test
+ void testArmMidPhase() {
+ when(obm.getPhase(300)).thenReturn(plains);
+ is.setBlockNumber(300);
+ fl.arm(is, plains);
+ assertEquals("", is.getFinalePending());
+ }
+
+ @Test
+ void testArmDisabled() {
+ settings.setPhaseFinales(false);
+ when(obm.getPhase(700)).thenReturn(next);
+ is.setBlockNumber(700);
+ fl.arm(is, plains);
+ assertEquals("", is.getFinalePending());
+ }
+
+ @Test
+ void testArmNoFinale() {
+ plains.setFinale(null);
+ when(obm.getPhase(700)).thenReturn(next);
+ is.setBlockNumber(700);
+ fl.arm(is, plains);
+ assertEquals("", is.getFinalePending());
+ }
+
+ @Test
+ void testGateNothingPending() {
+ assertFalse(fl.gate(island, is, mockPlayer, block));
+ verify(world, never()).spawnEntity(any(), any(EntityType.class));
+ }
+
+ @Test
+ void testGateSummonsBoss() {
+ summon();
+ verify(world).spawnEntity(any(), eq(EntityType.ZOMBIE));
+ verify(pim).callEvent(any(PhaseFinaleStartEvent.class));
+ verify(boss).setPersistent(false);
+ verify(boss).setTarget(mockPlayer);
+ verify(boss).getAttribute(Attribute.SCALE);
+ verify(attribute).setBaseValue(2D);
+ verify(world).strikeLightningEffect(any());
+ verify(mockPlayer).showBossBar(any());
+ assertTrue(fl.isActive(island));
+ // Still pending until it is dead
+ assertEquals(PLAINS, is.getFinalePending());
+ }
+
+ @Test
+ void testGateOnlyOneBoss() {
+ summon();
+ assertTrue(fl.gate(island, is, mockPlayer, block));
+ verify(world, times(1)).spawnEntity(any(), eq(EntityType.ZOMBIE));
+ }
+
+ @Test
+ void testGateMinionCannotSummon() {
+ is.setFinalePending(PLAINS);
+ assertTrue(fl.gate(island, is, null, block));
+ verify(world, never()).spawnEntity(any(), any(EntityType.class));
+ assertEquals(PLAINS, is.getFinalePending());
+ }
+
+ @Test
+ void testGatePeacefulWaives() {
+ when(world.getDifficulty()).thenReturn(Difficulty.PEACEFUL);
+ is.setFinalePending(PLAINS);
+ assertFalse(fl.gate(island, is, mockPlayer, block));
+ assertEquals("", is.getFinalePending());
+ }
+
+ @Test
+ void testGateDisabledWaives() {
+ settings.setPhaseFinales(false);
+ is.setFinalePending(PLAINS);
+ assertFalse(fl.gate(island, is, mockPlayer, block));
+ assertEquals("", is.getFinalePending());
+ }
+
+ @Test
+ void testGateOtherPhaseWaives() {
+ // The count was moved somewhere else while a finale was pending
+ is.setFinalePending(PLAINS);
+ is.setPhaseName("Winter");
+ assertFalse(fl.gate(island, is, mockPlayer, block));
+ assertEquals("", is.getFinalePending());
+ }
+
+ @Test
+ void testGateSpawnFailureWaives() {
+ when(boss.isValid()).thenReturn(false);
+ is.setFinalePending(PLAINS);
+ assertFalse(fl.gate(island, is, mockPlayer, block));
+ assertEquals("", is.getFinalePending());
+ assertFalse(fl.isActive(island));
+ }
+
+ @Test
+ void testEnvironmentalDamageCancelled() {
+ summon();
+ EntityDamageEvent e = mock(EntityDamageEvent.class);
+ when(e.getEntity()).thenReturn(boss);
+ when(e.getCause()).thenReturn(DamageCause.SUFFOCATION);
+ fl.onBossDamage(e);
+ verify(e).setCancelled(true);
+ }
+
+ @Test
+ void testPlayerDamageAllowed() {
+ summon();
+ EntityDamageByEntityEvent e = mock(EntityDamageByEntityEvent.class);
+ when(e.getEntity()).thenReturn(boss);
+ when(e.getCause()).thenReturn(DamageCause.ENTITY_ATTACK);
+ when(e.getDamager()).thenReturn(mockPlayer);
+ fl.onBossDamage(e);
+ verify(e, never()).setCancelled(true);
+ }
+
+ @Test
+ void testPlayerArrowAllowedMobArrowNot() {
+ summon();
+ Arrow arrow = mock(Arrow.class);
+ when(arrow.getShooter()).thenReturn(mockPlayer);
+ EntityDamageByEntityEvent e = mock(EntityDamageByEntityEvent.class);
+ when(e.getEntity()).thenReturn(boss);
+ when(e.getCause()).thenReturn(DamageCause.PROJECTILE);
+ when(e.getDamager()).thenReturn(arrow);
+ fl.onBossDamage(e);
+ verify(e, never()).setCancelled(true);
+
+ Arrow arrow2 = mock(Arrow.class);
+ EntityDamageByEntityEvent e2 = mock(EntityDamageByEntityEvent.class);
+ when(e2.getEntity()).thenReturn(boss);
+ when(e2.getCause()).thenReturn(DamageCause.PROJECTILE);
+ when(e2.getDamager()).thenReturn(arrow2);
+ fl.onBossDamage(e2);
+ verify(e2).setCancelled(true);
+ }
+
+ @Test
+ void testVoidRespawn() {
+ summon();
+ EntityDamageEvent e = mock(EntityDamageEvent.class);
+ when(e.getEntity()).thenReturn(boss);
+ when(e.getCause()).thenReturn(DamageCause.VOID);
+ fl.onBossDamage(e);
+ verify(e).setCancelled(true);
+ verify(boss).teleport(any(Location.class));
+ }
+
+ @Test
+ void testVoidKillsWhenRespawnOff() {
+ plains.setFinale(finale(false));
+ summon();
+ EntityDamageEvent e = mock(EntityDamageEvent.class);
+ when(e.getEntity()).thenReturn(boss);
+ when(e.getCause()).thenReturn(DamageCause.VOID);
+ fl.onBossDamage(e);
+ verify(e, never()).setCancelled(true);
+ verify(boss, never()).teleport(any(Location.class));
+ }
+
+ @Test
+ void testOtherEntityDamageIgnored() {
+ summon();
+ EntityDamageEvent e = mock(EntityDamageEvent.class);
+ Zombie bystander = mock(Zombie.class);
+ when(bystander.getUniqueId()).thenReturn(UUID.randomUUID());
+ when(e.getEntity()).thenReturn(bystander);
+ fl.onBossDamage(e);
+ verify(e, never()).setCancelled(true);
+ }
+
+ @Test
+ void testBossDeathWins() {
+ summon();
+ EntityDeathEvent e = mock(EntityDeathEvent.class);
+ when(e.getEntity()).thenReturn(boss);
+ fl.onDeath(e);
+ assertEquals("", is.getFinalePending());
+ assertTrue(is.getDefeatedFinales().contains(PLAINS));
+ assertFalse(fl.isActive(island));
+ verify(world).dropItem(any(), eq(new ItemStack(Material.IRON_INGOT, 8)));
+ verify(pim).callEvent(any(PhaseFinaleEndEvent.class));
+ verify(blis).saveIsland(island);
+ verify(mockPlayer).hideBossBar(any());
+ // The way is open
+ assertFalse(fl.gate(island, is, mockPlayer, block));
+ }
+
+ @Test
+ void testBossRemovedIsNotAWin() {
+ summon();
+ when(boss.isValid()).thenReturn(false);
+ fl.tickAll();
+ assertFalse(fl.isActive(island));
+ assertEquals(PLAINS, is.getFinalePending());
+ assertEquals(0, is.getFinaleFails());
+ assertTrue(is.getDefeatedFinales().isEmpty());
+ }
+
+ @Test
+ void testEmptyIslandBossRetreatsAndMercy() {
+ summon();
+ PlayerDeathEvent death = mock(PlayerDeathEvent.class);
+ when(death.getEntity()).thenReturn(mockPlayer);
+ fl.onPlayerDeath(death);
+ when(world.getPlayers()).thenReturn(List.of());
+ for (int i = 0; i < FinaleListener.EMPTY_CHECKS; i++) {
+ fl.tickAll();
+ }
+ assertFalse(fl.isActive(island));
+ verify(boss).remove();
+ assertEquals(PLAINS, is.getFinalePending());
+ assertEquals(1, is.getFinaleFails());
+ }
+
+ @Test
+ void testLeash() {
+ summon();
+ when(island.onIsland(any())).thenReturn(false);
+ // The player is still a fighter
+ when(island.onIsland(mockPlayer.getLocation())).thenReturn(true);
+ fl.tickAll();
+ verify(boss).teleport(any(Location.class));
+ }
+
+ @Test
+ void testBossCannotChangeBlocks() {
+ summon();
+ EntityChangeBlockEvent e = mock(EntityChangeBlockEvent.class);
+ when(e.getEntity()).thenReturn(boss);
+ fl.onChangeBlock(e);
+ verify(e).setCancelled(true);
+ }
+
+ @Test
+ void testClear() {
+ summon();
+ fl.clear(island, is);
+ assertFalse(fl.isActive(island));
+ assertEquals("", is.getFinalePending());
+ verify(boss).remove();
+ }
+
+ @Test
+ void testOnDisable() {
+ summon();
+ fl.onDisable();
+ assertFalse(fl.isActive(island));
+ verify(boss).remove();
+ // Still pending for after the restart
+ assertEquals(PLAINS, is.getFinalePending());
+ }
+}
diff --git a/src/test/java/world/bentobox/aoneblock/oneblocks/OneBlocksManagerTest3.java b/src/test/java/world/bentobox/aoneblock/oneblocks/OneBlocksManagerTest3.java
index 0cc9fb4f..54268749 100644
--- a/src/test/java/world/bentobox/aoneblock/oneblocks/OneBlocksManagerTest3.java
+++ b/src/test/java/world/bentobox/aoneblock/oneblocks/OneBlocksManagerTest3.java
@@ -1,5 +1,6 @@
package world.bentobox.aoneblock.oneblocks;
+import org.bukkit.entity.EntityType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -1512,4 +1513,81 @@ void testLoadPhases_fixedBlockChestWithInvalidItem() throws Exception {
verify(plugin).logError(org.mockito.ArgumentMatchers.contains("CHEST_WITH item is invalid"));
}
+
+ /**
+ * Test method for
+ * {@link world.bentobox.aoneblock.oneblocks.OneBlocksManager#addFinale(OneBlockPhase, org.bukkit.configuration.ConfigurationSection)}.
+ */
+ @Test
+ void testAddFinale() throws Exception {
+ YamlConfiguration cfg = new YamlConfiguration();
+ cfg.loadFromString("""
+ finale:
+ boss: zombie
+ name: 'Boss'
+ health: 150
+ scale: 2.5
+ damage: 6
+ void-respawn: false
+ warning: 10
+ minions:
+ SKELETON: 3
+ NOT_A_MOB: 2
+ drops:
+ DIAMOND: 4
+ commands:
+ - 'say hi'
+ """);
+ OneBlockPhase phase = new OneBlockPhase("0");
+ phase.setPhaseName("Plains");
+ obm.addFinale(phase, cfg);
+ PhaseFinale f = phase.getFinale();
+ assertEquals(EntityType.ZOMBIE, f.boss());
+ assertEquals("Boss", f.name());
+ assertEquals(150D, f.health());
+ assertEquals(2.5D, f.scale());
+ assertEquals(6D, f.damage());
+ assertEquals(0D, f.speed());
+ assertFalse(f.voidRespawn());
+ assertEquals(10, f.warning());
+ assertEquals(java.util.Map.of(EntityType.SKELETON, 3), f.minions());
+ assertEquals(java.util.Map.of(Material.DIAMOND, 4), f.drops());
+ assertEquals(java.util.List.of("say hi"), f.commands());
+ assertTrue(f.firstTimeCommands().isEmpty());
+ }
+
+ /**
+ * A phase without a finale section, or with a bad boss, has no finale.
+ */
+ @Test
+ void testAddFinaleNoneOrBad() throws Exception {
+ OneBlockPhase phase = new OneBlockPhase("0");
+ phase.setPhaseName("Plains");
+ obm.addFinale(phase, new YamlConfiguration());
+ assertNull(phase.getFinale());
+ YamlConfiguration cfg = new YamlConfiguration();
+ cfg.loadFromString("finale:\n boss: ARROW\n");
+ obm.addFinale(phase, cfg);
+ assertNull(phase.getFinale());
+ }
+
+ /**
+ * Every shipped phase ends in a boss that this server version understands.
+ */
+ @Test
+ void testShippedPhasesHaveFinales() {
+ File[] files = new File("src/main/resources/phases")
+ .listFiles((d, n) -> n.endsWith(".yml") && !n.endsWith("_chests.yml") && !n.contains("goto"));
+ assertTrue(files.length > 10);
+ for (File file : files) {
+ YamlConfiguration cfg = YamlConfiguration.loadConfiguration(file);
+ String key = cfg.getKeys(false).iterator().next();
+ OneBlockPhase phase = new OneBlockPhase(key);
+ phase.setPhaseName(file.getName());
+ obm.addFinale(phase, cfg.getConfigurationSection(key));
+ assertNotNull(phase.getFinale(), file.getName());
+ assertTrue(phase.getFinale().health() <= 1024D / 2.5D, file.getName() + " health exceeds the server cap when scaled");
+ assertFalse(phase.getFinale().drops().isEmpty(), file.getName());
+ }
+ }
}