下面列出了怎么用org.bukkit.block.CreatureSpawner的API类实例代码及写法,或者点击链接到github查看源代码。
@EventHandler
public void onSpawnerSpawn(SpawnerSpawnEvent event) {
try {
final Location location = event.getLocation();
final IslandManager islandManager = IridiumSkyblock.getIslandManager();
final Island island = islandManager.getIslandViaLocation(location);
if (island == null) return;
if (island.getSpawnerBooster() == 0) return;
final IridiumSkyblock plugin = IridiumSkyblock.getInstance();
final CreatureSpawner spawner = event.getSpawner();
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> spawner.setDelay(spawner.getDelay() / 2), 0);
} catch (Exception e) {
IridiumSkyblock.getInstance().sendErrorMessage(e);
}
}
@SuppressWarnings("null")
@Override
public void change(final Event e, final @Nullable Object[] delta, final ChangeMode mode) {
for (Block b : getExpr().getArray(e)) {
if (b.getType() != MATERIAL_SPAWNER)
continue;
CreatureSpawner s = (CreatureSpawner) b.getState();
switch (mode) {
case SET:
s.setSpawnedType(toBukkitEntityType((EntityData) delta[0]));
break;
case RESET:
s.setSpawnedType(org.bukkit.entity.EntityType.PIG);
break;
}
s.update(); // Actually trigger the spawner's update
}
}
/**
* Calculates the spawner worth of a chunk.
*
* @param chunk the chunk.
* @param spawners the spawner totals to add to.
* @return the chunk worth in spawners.
*/
private double getSpawnerWorth(Chunk chunk, Map<EntityType, Integer> spawners) {
int count;
double worth = 0;
for (BlockState blockState : chunk.getTileEntities()) {
if (!(blockState instanceof CreatureSpawner)) {
continue;
}
CreatureSpawner spawner = (CreatureSpawner) blockState;
EntityType spawnType = spawner.getSpawnedType();
int stackSize = plugin.getSpawnerStackerHook().getStackSize(spawner);
double blockPrice = plugin.getSettings().getSpawnerPrice(spawnType) * stackSize;
worth += blockPrice;
if (blockPrice != 0) {
count = spawners.getOrDefault(spawnType, 0);
spawners.put(spawnType, count + stackSize);
}
}
return worth;
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void updateWorth(SpawnerMultiplierChangeEvent event) {
// Do nothing if this area should not be calculated.
Block block = event.getBlock();
String factionId = plugin.getFactionsHook().getFactionAt(block);
if (plugin.getSettings().getIgnoredFactionIds().contains(factionId)) {
return;
}
// Get the worth type and price of this event.
int difference = event.getNewMultiplier() - event.getOldMultiplier();
WorthType worthType = WorthType.SPAWNER;
Map<Material, Integer> materials = new HashMap<>();
Map<EntityType, Integer> spawners = new HashMap<>();
EntityType spawnType = ((CreatureSpawner) block.getState()).getSpawnedType();
double price = difference * plugin.getSettings().getSpawnerPrice(spawnType);
spawners.put(spawnType, difference);
RecalculateReason reason = difference > 0 ? RecalculateReason.PLACE : RecalculateReason.BREAK;
// Add block price to the count.
plugin.getWorthManager().add(block.getChunk(), reason, worthType, price, materials, spawners);
}
@Override
public BlockPlaceHandler getItemHandler() {
return (p, e, item) -> {
// We need to explicitly ignore the lore here
if (SlimefunUtils.isItemSimilar(item, SlimefunItems.REPAIRED_SPAWNER, false, false)) {
Optional<EntityType> entity = getEntityType(item);
if (entity.isPresent()) {
CreatureSpawner spawner = (CreatureSpawner) e.getBlock().getState();
spawner.setSpawnedType(entity.get());
spawner.update(true, false);
}
return true;
}
else {
return false;
}
};
}
private void placeSlimefunBlock(SlimefunItem sfItem, ItemStack item, Block block, Dispenser dispenser) {
block.setType(item.getType());
BlockStorage.store(block, sfItem.getID());
block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, item.getType());
if (item.getType() == Material.SPAWNER && sfItem instanceof RepairedSpawner) {
Optional<EntityType> entity = ((RepairedSpawner) sfItem).getEntityType(item);
if (entity.isPresent()) {
CreatureSpawner spawner = (CreatureSpawner) block.getState();
spawner.setSpawnedType(entity.get());
spawner.update(true, false);
}
}
if (dispenser.getInventory().containsAtLeast(item, 2)) {
dispenser.getInventory().removeItem(new CustomItem(item, 1));
}
else {
Slimefun.runSync(() -> dispenser.getInventory().removeItem(item), 2L);
}
}
private ItemStack breakSpawner(Block b) {
// If the spawner's BlockStorage has BlockInfo, then it's not a vanilla spawner and
// should not give a broken spawner.
ItemStack spawner = SlimefunItems.BROKEN_SPAWNER.clone();
if (BlockStorage.hasBlockInfo(b)) {
spawner = SlimefunItems.REPAIRED_SPAWNER.clone();
}
ItemMeta im = spawner.getItemMeta();
List<String> lore = im.getLore();
for (int i = 0; i < lore.size(); i++) {
if (lore.get(i).contains("<Type>")) {
lore.set(i, lore.get(i).replace("<Type>", ChatUtils.humanize(((CreatureSpawner) b.getState()).getSpawnedType().toString())));
}
}
im.setLore(lore);
spawner.setItemMeta(im);
return spawner;
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onPlayerInteractMobSpawner(PlayerInteractEvent evt) {
if (plugin.getConfig().getBoolean("features.monsterEggMobSpawner", true)) {
if (evt.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (evt.getPlayer().getItemInHand().getType() == Material.MONSTER_EGG && evt.getClickedBlock().getType() == Material.MOB_SPAWNER) {
ItemStack egg = evt.getPlayer().getItemInHand();
CreatureSpawner cs = (CreatureSpawner) evt.getClickedBlock().getState();
cs.setSpawnedType(EntityType.fromId(egg.getData().getData()));
cs.update(true);
evt.setUseItemInHand(Event.Result.DENY);
evt.setCancelled(true);
}
}
}
}
public void initBlocks() {
updating = true;
final Config config = IridiumSkyblock.getConfiguration();
final IridiumSkyblock plugin = IridiumSkyblock.getInstance();
final BukkitScheduler scheduler = Bukkit.getScheduler();
final Runnable task = new InitIslandBlocksRunnable(this, config.blocksPerTick, () -> {
if (IridiumSkyblock.blockspertick != -1) {
config.blocksPerTick = IridiumSkyblock.blockspertick;
IridiumSkyblock.blockspertick = -1;
}
scheduler.cancelTask(initBlocks);
initBlocks = -1;
plugin.updatingBlocks = false;
updating = false;
valuableBlocks.clear();
spawners.clear();
for (Location location : tempValues) {
final Block block = location.getBlock();
if (!(Utils.isBlockValuable(block) || !(block.getState() instanceof CreatureSpawner))) continue;
final Material material = block.getType();
final XMaterial xmaterial = XMaterial.matchXMaterial(material);
valuableBlocks.compute(xmaterial.name(), (xmaterialName, original) -> {
if (original == null) return 1;
return original + 1;
});
}
tempValues.clear();
calculateIslandValue();
});
initBlocks = scheduler.scheduleSyncRepeatingTask(plugin, task, 0, 1);
}
public void forceInitBlocks(CommandSender sender, int blocksPerTick, String name) {
final Config config = IridiumSkyblock.getConfiguration();
final Messages messages = IridiumSkyblock.getMessages();
if (sender != null)
sender.sendMessage(Utils.color(messages.updateStarted
.replace("%player%", name)
.replace("%prefix%", config.prefix)));
updating = true;
final IridiumSkyblock plugin = IridiumSkyblock.getInstance();
final BukkitScheduler scheduler = Bukkit.getScheduler();
final Runnable task = new InitIslandBlocksWithSenderRunnable(this, blocksPerTick, sender, name, () -> {
if (sender != null)
sender.sendMessage(Utils.color(messages.updateFinished
.replace("%player%", name)
.replace("%prefix%", config.prefix)));
scheduler.cancelTask(initBlocks);
initBlocks = -1;
updating = false;
valuableBlocks.clear();
spawners.clear();
for (Location location : tempValues) {
final Block block = location.getBlock();
if (!(Utils.isBlockValuable(block) || !(block.getState() instanceof CreatureSpawner))) continue;
final Material material = block.getType();
final XMaterial xmaterial = XMaterial.matchXMaterial(material);
valuableBlocks.compute(xmaterial.name(), (xmaterialName, original) -> {
if (original == null) return 1;
return original + 1;
});
}
tempValues.clear();
calculateIslandValue();
});
initBlocks = scheduler.scheduleSyncRepeatingTask(plugin, task, 0, 1);
}
@Override
public Long next() {
if (currentX < islandMaxX) {
currentX++;
} else if (currentZ < islandMaxZ) {
currentX = islandMinX;
currentZ++;
} else if (currentY < maxWorldHeight) {
currentX = islandMinX;
currentZ = islandMinZ;
currentY++;
} else if (config.netherIslands && currentWorld.getName().equals(config.worldName)) {
currentWorld = islandManager.getNetherWorld();
currentX = islandMinX;
currentY = 0;
currentZ = islandMinZ;
} else {
throw new NoSuchElementException();
}
if (plugin.updatingBlocks) {
final Location location = new Location(currentWorld, currentX, currentY, currentZ);
final Block block = location.getBlock();
if (Utils.isBlockValuable(block) && !(block.getState() instanceof CreatureSpawner))
island.tempValues.add(location);
}
return currentBlock++;
}
private void handlePlacement(Player player, Block block, EntityType type, double cost) {
CreatureSpawner spawner = (CreatureSpawner) block.getState();
spawner.setSpawnedType(type);
spawner.update();
if (plugin.getConfigurationHandler().getBoolean("placing", "log")) {
Location loc = block.getLocation();
System.out.println("[MineableSpawners] Player " + player.getName() + " placed a " + type.name().toLowerCase() + " spawner at x:" + loc.getX() + ", y:" + loc.getY() + ", z:" + loc.getZ() + " (" + loc.getWorld().getName() + ")");
}
if (cost > 0) {
player.sendMessage(plugin.getConfigurationHandler().getMessage("placing", "transaction-success").replace("%type%", Chat.uppercaseStartingLetters(type.name())).replace("%cost%", df.format(cost).replace("%balance%", df.format(plugin.getEcon().getBalance(player)))));
}
}
@Override
@Nullable
public EntityData convert(final Block b) {
if (b.getType() != MATERIAL_SPAWNER)
return null;
return toSkriptEntityData(((CreatureSpawner) b.getState()).getSpawnedType());
}
@Override
public int getStackSize(CreatureSpawner spawner) {
if (api == null) {
return 1;
}
return api.getSpawnerMultiplier(spawner.getLocation());
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void updateWorth(SpawnerChangeEvent event) {
CreatureSpawner spawner = (CreatureSpawner) event.getSpawner().getState();
int oldMultiplier = event.getOldMulti();
int newMultiplier = event.getCurrentMulti();
SpawnerMultiplierChangeEvent event1 = new SpawnerMultiplierChangeEvent(spawner, oldMultiplier, newMultiplier);
if (plugin.getServer().isPrimaryThread()) {
plugin.getServer().getPluginManager().callEvent(event1);
return;
}
plugin.getServer().getScheduler().runTask(plugin, () ->
plugin.getServer().getPluginManager().callEvent(event1));
}
/**
* Sets spawners to their type
* @param e - event
*/
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onSpawnerBlockPlace(final BlockPlaceEvent e) {
if (DEBUG)
plugin.getLogger().info("DEBUG: block place");
if (inWorld(e.getPlayer()) && Util.playerIsHolding(e.getPlayer(), Material.MOB_SPAWNER)) {
if (DEBUG)
plugin.getLogger().info("DEBUG: in world");
// Get item in hand
for (ItemStack item : Util.getPlayerInHandItems(e.getPlayer())) {
if (item.getType().equals(Material.MOB_SPAWNER) && item.hasItemMeta() && item.getItemMeta().hasLore()) {
if (DEBUG)
plugin.getLogger().info("DEBUG: spawner in hand with lore");
List<String> lore = item.getItemMeta().getLore();
if (!lore.isEmpty()) {
if (DEBUG)
plugin.getLogger().info("DEBUG: lore is not empty");
for (EntityType type : EntityType.values()) {
if (lore.get(0).equals(Util.prettifyText(type.name()))) {
// Found the spawner type
if (DEBUG)
plugin.getLogger().info("DEBUG: found type");
e.getBlock().setType(Material.MOB_SPAWNER);
CreatureSpawner cs = (CreatureSpawner)e.getBlock().getState();
cs.setSpawnedType(type);
}
}
// Spawner type not found - do anything : it may be another plugin's spawner
}
}
}
}
}
public static int getSpawnerAmount(CreatureSpawner spawner) {
return ASAPI.getSpawnerAmount(spawner.getBlock());
}
public static int getSpawnerAmount(CreatureSpawner spawner) {
return com.songoda.ultimatestacker.UltimateStacker.getInstance().getSpawnerStackManager().getSpawner(spawner.getBlock()).getAmount();
}
public static int getSpawnerAmount(CreatureSpawner spawner) {
return MergedSpawnerAPI.getInstance().getCountFor(spawner.getBlock());
}
public static int getSpawnerAmount(CreatureSpawner spawner) {
return WildStackerAPI.getSpawnersAmount(spawner);
}
public static int getSpawnerAmount(CreatureSpawner spawner) {
return com.songoda.epicspawners.EpicSpawners.getInstance().getSpawnerManager().getSpawnerFromWorld(spawner.getLocation()).getSpawnCount();
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onMonitorEntityExplode(EntityExplodeEvent event) {
try {
final Entity entity = event.getEntity();
final Location location = entity.getLocation();
final IslandManager islandManager = IridiumSkyblock.getIslandManager();
if (!islandManager.isIslandWorld(location)) return;
final UUID uuid = entity.getUniqueId();
final IridiumSkyblock plugin = IridiumSkyblock.getInstance();
final Map<UUID, Island> entities = plugin.entities;
Island island = entities.get(uuid);
if (island != null && island.isInIsland(location)) {
event.setCancelled(true);
entity.remove();
entities.remove(uuid);
return;
}
island = islandManager.getIslandViaLocation(location);
if (island == null) return;
for (Block block : event.blockList()) {
if (!island.isInIsland(block.getLocation())) {
final BlockState state = block.getState();
IridiumSkyblock.nms.setBlockFast(block, 0, (byte) 0);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> state.update(true, true));
}
if (!Utils.isBlockValuable(block)) continue;
if (!(block.getState() instanceof CreatureSpawner)) {
final Material material = block.getType();
final XMaterial xmaterial = XMaterial.matchXMaterial(material);
island.valuableBlocks.computeIfPresent(xmaterial.name(), (name, original) -> original - 1);
}
if (island.updating)
island.tempValues.remove(block.getLocation());
}
island.calculateIslandValue();
} catch (Exception ex) {
IridiumSkyblock.getInstance().sendErrorMessage(ex);
}
}
public static boolean isBlockValuable(Block b) {
return IridiumSkyblock.getBlockValues().blockvalue.containsKey(XMaterial.matchXMaterial(b.getType())) || b.getState() instanceof CreatureSpawner || IridiumSkyblock.getConfiguration().limitedBlocks.containsKey(XMaterial.matchXMaterial(b.getType()));
}
public SpawnerSpawnEvent(final Entity spawnee, final CreatureSpawner spawner) {
super(spawnee);
this.spawner = spawner;
}
public CreatureSpawner getSpawner() {
return spawner;
}
public void execute(MineableSpawners plugin, CommandSender sender, String type) {
if (!(sender instanceof Player)) {
System.out.println("[MineableSpawners] Only players can run this command!");
return;
}
Player player = (Player) sender;
if (plugin.getConfigurationHandler().getList("set", "blacklisted-worlds").contains(player.getWorld().getName())) {
player.sendMessage(plugin.getConfigurationHandler().getMessage("set", "blacklisted"));
return;
}
EntityType entityType;
try {
entityType = EntityType.valueOf(type.toUpperCase());
} catch (IllegalArgumentException e) {
player.sendMessage(plugin.getConfigurationHandler().getMessage("set", "invalid-type"));
return;
}
if (plugin.getConfigurationHandler().getBoolean("set", "require-individual-permission")) {
if (!player.hasPermission("mineablespawners.set." + type.toLowerCase())) {
player.sendMessage(plugin.getConfigurationHandler().getMessage("set", "no-individual-permission"));
return;
}
}
Block target = player.getTargetBlock(invisibleBlocks, 5);
if (target.getState().getBlock().getType() != XMaterial.SPAWNER.parseMaterial()) {
player.sendMessage(plugin.getConfigurationHandler().getMessage("set", "not-looking-at"));
return;
}
CreatureSpawner spawner = (CreatureSpawner) target.getState();
String from = Chat.uppercaseStartingLetters(spawner.getSpawnedType().name());
String to = Chat.uppercaseStartingLetters(type);
if (from.equals(to)) {
player.sendMessage(plugin.getConfigurationHandler().getMessage("set", "already-type"));
return;
}
spawner.setSpawnedType(entityType);
spawner.update();
player.sendMessage(plugin.getConfigurationHandler().getMessage("set", "success").replace("%from%", from).replace("%to%", to));
}
@EventHandler
public void onEggChange(PlayerInteractEvent e) {
if (!e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) {
return;
}
Player player = e.getPlayer();
ItemStack itemInHand = e.getItem();
if (itemInHand == null || itemInHand.getType().equals(Material.AIR)) {
return;
}
String itemName = itemInHand.getType().name();
Material targetBlock = e.getClickedBlock().getType();
if (targetBlock != XMaterial.SPAWNER.parseMaterial() || !itemName.contains("SPAWN_EGG")) {
return;
}
if (plugin.getConfigurationHandler().getList("eggs", "blacklisted-worlds").contains(player.getWorld().getName())) {
e.setCancelled(true);
player.sendMessage(plugin.getConfigurationHandler().getMessage("eggs", "blacklisted"));
return;
}
if (plugin.getConfigurationHandler().getBoolean("eggs", "require-permission")) {
if (!player.hasPermission("mineablespawners.eggchange")) {
e.setCancelled(true);
player.sendMessage(plugin.getConfigurationHandler().getMessage("eggs", "no-permission"));
return;
}
}
String to = itemName.split("_SPAWN_EGG")[0].replace("_", " ").toLowerCase();
if (plugin.getConfigurationHandler().getBoolean("eggs", "require-individual-permission")) {
if (!player.hasPermission("mineablespawners.eggchange." + to.replace(" ", "_"))) {
e.setCancelled(true);
player.sendMessage(plugin.getConfigurationHandler().getMessage("eggs", "no-individual-permission"));
return;
}
}
CreatureSpawner spawner = (CreatureSpawner) e.getClickedBlock().getState();
String from = spawner.getSpawnedType().toString().replace("_", " ").toLowerCase();
if (from.equals(to)) {
e.setCancelled(true);
player.sendMessage(plugin.getConfigurationHandler().getMessage("eggs", "already-type"));
return;
}
player.sendMessage(plugin.getConfigurationHandler().getMessage("eggs", "success").replace("%from%", from).replace("%to%", to));
}
@EventHandler (ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onSpawnerExplode(EntityExplodeEvent e) {
if (!plugin.getConfigurationHandler().getBoolean("explode", "drop")) {
return;
}
for (Block block : e.blockList()) {
if (!block.getType().equals(XMaterial.SPAWNER.parseMaterial())) {
continue;
}
double dropChance = plugin.getConfigurationHandler().getDouble("explode", "chance")/100;
if (dropChance != 1) {
double random = Math.random();
if (random >= dropChance) {
return;
}
}
CreatureSpawner spawner = (CreatureSpawner) block.getState();
ItemStack item = new ItemStack(XMaterial.SPAWNER.parseMaterial());
ItemMeta meta = item.getItemMeta();
String mobFormatted = Chat.uppercaseStartingLetters(spawner.getSpawnedType().toString());
meta.setDisplayName(plugin.getConfigurationHandler().getMessage("global", "name").replace("%mob%", mobFormatted));
List<String> newLore = new ArrayList<>();
if (plugin.getConfigurationHandler().getList("global", "lore") != null && plugin.getConfigurationHandler().getBoolean("global", "lore-enabled")) {
for (String line : plugin.getConfigurationHandler().getList("global", "lore")) {
newLore.add(Chat.format(line).replace("%mob%", mobFormatted));
}
meta.setLore(newLore);
}
item.setItemMeta(meta);
item = plugin.getNmsHandler().setType(item, spawner.getSpawnedType());
block.getLocation().getWorld().dropItemNaturally(block.getLocation(), item);
}
}
@Override
public int getStackSize(CreatureSpawner spawner) {
return 1;
}
public SpawnerMultiplierChangeEvent(CreatureSpawner spawner, int oldMultiplier, int newMultiplier) {
super(spawner.getBlock());
this.spawner = spawner;
this.oldMultiplier = oldMultiplier;
this.newMultiplier = newMultiplier;
}