下面列出了怎么用org.bukkit.block.Block的API类实例代码及写法,或者点击链接到github查看源代码。
public ItemUseHandler onRightClick() {
return e -> {
Optional<Block> block = e.getClickedBlock();
if (block.isPresent()) {
Material material = block.get().getType();
// Cancel the Block placement if the Player sneaks or the Block is not interactable
if (e.getPlayer().isSneaking() || !isInteractable(material)) {
e.cancel();
}
else {
return;
}
}
if (edible && e.getPlayer().getFoodLevel() < 20) {
restoreHunger(e.getPlayer());
ItemUtils.consumeItem(e.getItem(), false);
}
};
}
@SuppressWarnings("deprecation")
public boolean set(Block block) {
Skull skull = (Skull) block.getState();
if(skullOwnerName != null){
skull.setOwner(skullOwnerName);
}
skull.setSkullType(skullType);
skull.setRotation(skullRotation);
skull.setRawData((byte) skullStanding);
// Texture update
if(skullTextureValue != null){
setSkullWithNonPlayerProfile(skullTextureValue, skullTextureSignature, skullOwnerUUID, skullOwnerName, skull);
}
skull.update(true, false);
return true;
}
public void previewEntireTemplate(Template tpl, Block cornerBlock, Player player) {
//HashMap<Chunk, Chunk> chunkUpdates = new HashMap<Chunk, Chunk>();
// NMSHandler nms = new NMSHandler();
PlayerBlockChangeUtil util = new PlayerBlockChangeUtil();
for (int x = 0; x < tpl.size_x; x++) {
for (int y = 0; y < tpl.size_y; y++) {
for (int z = 0; z < tpl.size_z; z++) {
Block b = cornerBlock.getRelative(x, y, z);
//b.setTypeIdAndData(tpl.blocks[x][y][z].getType(), (byte)tpl.blocks[x][y][z].getData(), false);
try {
util.addUpdateBlock("", new BlockCoord(b), tpl.blocks[x][y][z].getType(), tpl.blocks[x][y][z].getData());
// nms.setBlockFast(b.getWorld(), b.getX(), b.getY(), b.getZ(), tpl.blocks[x][y][z].getType(),
// (byte)tpl.blocks[x][y][z].getData());
} catch (Exception e) {
e.printStackTrace();
//throw new CivException("Couldn't build undo template unknown error:"+e.getMessage());
}
}
}
}
util.sendUpdate(player.getName());
}
/**
* Find a protection that is adjacent to another block on any of the block's 6
* sides
*
* @param block
* @param ignore
* @return
*/
public List<Protection> findAdjacentProtectionsOnAllSides(Block block, Block... ignore) {
BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST,
BlockFace.UP, BlockFace.DOWN};
List<Block> ignoreList = Arrays.asList(ignore);
List<Protection> found = new ArrayList<Protection>();
for (BlockFace face : faces) {
Protection protection;
Block adjacentBlock = block.getRelative(face);
if (!ignoreList.contains(adjacentBlock.getLocation())
&& (protection = findProtection(adjacentBlock.getLocation())) != null) {
found.add(protection);
}
}
return found;
}
private void dropFruitFromTree(Block block) {
for (int x = -1; x < 2; x++) {
for (int y = -1; y < 2; y++) {
for (int z = -1; z < 2; z++) {
// inspect a cube at the reference
Block fruit = block.getRelative(x, y, z);
if (fruit.isEmpty()) continue;
Location loc = fruit.getLocation();
SlimefunItem check = BlockStorage.check(loc);
if (check == null) continue;
for (Tree tree : ExoticGarden.getTrees()) {
if (check.getID().equalsIgnoreCase(tree.getFruitID())) {
BlockStorage.clearBlockInfo(loc);
ItemStack fruits = check.getItem();
fruit.getWorld().playEffect(loc, Effect.STEP_SOUND, Material.OAK_LEAVES);
fruit.getWorld().dropItemNaturally(loc, fruits);
fruit.setType(Material.AIR);
break;
}
}
}
}
}
}
public CraftBlockState(final Block block) {
this.world = (CraftWorld) block.getWorld();
this.x = block.getX();
this.y = block.getY();
this.z = block.getZ();
this.type = block.getTypeId();
this.light = block.getLightLevel();
this.chunk = (CraftChunk) block.getChunk();
this.flag = 3;
// Cauldron start - save TE data
TileEntity te = world.getHandle().getTileEntity(x, y, z);
if (te != null)
{
nbt = new NBTTagCompound();
te.writeToNBT(nbt);
}
else nbt = null;
// Cauldron end
createData(block.getData());
}
@Override
public void test() throws Exception {
if(!NBTInjector.isInjected())return;
if (!Bukkit.getWorlds().isEmpty()) {
World world = Bukkit.getWorlds().get(0);
try {
Block block = world.getBlockAt(world.getSpawnLocation().getBlockX(), 255,
world.getSpawnLocation().getBlockZ());
if (block.getType() == Material.AIR) {
block.setType(Material.CHEST);
NBTCompound comp = NBTInjector.getNbtData(block.getState());
comp.setString("Foo", "Bar");
if (!new NBTTileEntity(block.getState()).toString().contains("__extraData:{Foo:\"Bar\"}")) {
block.setType(Material.AIR);
throw new NbtApiException("Custom Data did not save to the Tile!");
}
block.setType(Material.AIR);
}
} catch (Exception ex) {
throw new NbtApiException("Wasn't able to use NBTTiles!", ex);
}
}
}
public void tick(Block b) {
if (!regulator.equals(b.getLocation())) {
SimpleHologram.update(b, "&4Multiple Cargo Regulators connected");
return;
}
super.tick();
if (connectorNodes.isEmpty() && terminusNodes.isEmpty()) {
SimpleHologram.update(b, "&cNo Cargo Nodes found");
}
else {
SimpleHologram.update(b, "&7Status: &a&lONLINE");
Map<Integer, List<Location>> output = mapOutputNodes();
// Chest Terminal Stuff
Set<Location> destinations = new HashSet<>();
List<Location> output16 = output.get(16);
if (output16 != null) {
destinations.addAll(output16);
}
Slimefun.runSync(() -> run(b, destinations, output));
}
}
/**
* Calculate maximum/current health
*/
protected void recalculateHealth() {
// We only need blockMaterialHealth if there are destroyable blocks that are
// replaced by other destroyable blocks when broken.
if(this.isAffectedByBlockReplacementRules()) {
this.blockMaterialHealth = new HashMap<>();
this.buildMaterialHealthMap();
} else {
this.blockMaterialHealth = null;
this.maxHealth = (int) this.blockRegion.blockVolume();
this.health = 0;
for(Block block : this.blockRegion.getBlocks(match.getWorld())) {
if(this.hasMaterial(block.getState().getData())) {
this.health++;
}
}
}
}
protected Inventory findOutputChest(Block b, ItemStack output) {
for (BlockFace face : outputFaces) {
Block potentialOutput = b.getRelative(face);
if (potentialOutput.getType() == Material.CHEST) {
String id = BlockStorage.checkID(potentialOutput);
if (id != null && id.equals("OUTPUT_CHEST")) {
// Found the output chest! Now, let's check if we can fit the product in it.
Inventory inv = ((Chest) potentialOutput.getState()).getInventory();
if (InvUtils.fits(inv, output)) {
return inv;
}
}
}
}
return null;
}
@Override
protected Boolean execute(String playerID) throws QuestRuntimeException {
Player p = PlayerConverter.getPlayer(playerID);
Block lookingAt = p.getTargetBlock(null, 6);
if (loc != null) {
Location location = loc.getLocation(playerID);
Location to = lookingAt.getLocation();
if (location.getBlockX() != to.getBlockX()
|| location.getBlockY() != to.getBlockY()
|| location.getBlockZ() != to.getBlockZ()) return false;
}
if (selector != null) {
return selector.match(lookingAt);
}
return true;
}
public static boolean setDirection(Block block, BlockFace facing) {
if (XMaterial.ISFLAT) {
if (!(block.getBlockData() instanceof Directional)) return false;
Directional direction = (Directional) block.getBlockData();
direction.setFacing(facing);
return true;
}
BlockState state = block.getState();
MaterialData data = state.getData();
if (data instanceof org.bukkit.material.Directional) {
((org.bukkit.material.Directional) data).setFacingDirection(facing);
state.update(true);
return true;
}
return false;
}
public BlockCoord generatesCobble(int id, Block b)
{
int mirrorID1 = (id == CivData.WATER_RUNNING || id == CivData.WATER ? CivData.LAVA_RUNNING : CivData.WATER_RUNNING);
int mirrorID2 = (id == CivData.WATER_RUNNING || id == CivData.WATER ? CivData.LAVA : CivData.WATER);
for(BlockFace face : faces)
{
Block r = b.getRelative(face, 1);
if(ItemManager.getId(r) == mirrorID1 || ItemManager.getId(r) == mirrorID2)
{
return new BlockCoord(r);
}
}
return null;
}
public Uncarried(Flag flag, Post post, @Nullable Location location) {
super(flag, post);
if (location == null) location = flag.getReturnPoint(post);
this.location =
new Location(
location.getWorld(),
location.getBlockX() + 0.5,
location.getBlockY(),
location.getBlockZ() + 0.5,
location.getYaw(),
location.getPitch());
Block block = this.location.getBlock();
if (block.getType() == Material.STANDING_BANNER) {
// Banner may already be here at match start
this.oldBlock = BlockStates.cloneWithMaterial(block, Material.AIR);
} else {
this.oldBlock = block.getState();
}
this.oldBase = block.getRelative(BlockFace.DOWN).getState();
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPrimeTNT(ExplosionPrimeEvent event) {
if (event.getEntity() instanceof TNTPrimed) {
Block block = event.getEntity().getLocation().getBlock();
if (block.getType() == Material.TNT) {
ParticipantState player;
if (event instanceof ExplosionPrimeByEntityEvent) {
player = Trackers.getOwner(((ExplosionPrimeByEntityEvent) event).getPrimer());
} else {
player = null;
}
callEvent(event, block.getState(), BlockStates.toAir(block), player);
}
}
}
@EventHandler
public void onPistonRetract(BlockPistonRetractEvent e) {
if (e.isSticky()) {
for (Block b : e.getBlocks()) {
if (BlockStorage.hasBlockInfo(b) || (b.getRelative(e.getDirection()).getType() == Material.AIR && BlockStorage.hasBlockInfo(b.getRelative(e.getDirection())))) {
e.setCancelled(true);
return;
}
}
}
}
@Override
public PhysicalInfo resolveBlock(Block block) {
TrackerInfo info = blocks.get(block);
if(info instanceof PhysicalInfo) {
return (PhysicalInfo) info;
} else if(info instanceof OwnerInfo) {
return new BlockInfo(block.getState(), ((OwnerInfo) info).getOwner());
} else {
return new BlockInfo(block.getState());
}
}
@EventHandler(ignoreCancelled = true)
public void onBlockBreak(BlockBreakEvent e) {
final Block b = e.getBlock();
if (shopUtils.isShop(b.getLocation())) {
final Shop shop = shopUtils.getShop(e.getBlock().getLocation());
Player p = e.getPlayer();
if (p.isSneaking() && Utils.hasAxeInHand(p)) {
plugin.debug(String.format("%s tries to break %s's shop (#%d)", p.getName(), shop.getVendor().getName(), shop.getID()));
if (shop.getShopType() == Shop.ShopType.ADMIN) {
if (p.hasPermission(Permissions.REMOVE_ADMIN)) {
remove(shop, b, p);
return;
}
} else {
if (shop.getVendor().getUniqueId().equals(p.getUniqueId()) || p.hasPermission(Permissions.REMOVE_OTHER)) {
remove(shop, b, p);
return;
}
}
}
if (shop.getItem() != null) {
shop.getItem().resetForPlayer(p);
}
e.setCancelled(true);
e.getPlayer().sendMessage(LanguageUtils.getMessage(Message.CANNOT_BREAK_SHOP));
}
}
@Override
@Nullable
public Iterator<Block> iterator(final Event e) {
try {
final Expression<Direction> direction = this.direction;
if (direction != null) {
if (!from.isSingle()) {
return new ArrayIterator<>(get(e));
}
final Object o = from.getSingle(e);
if (o == null)
return null;
final Location l = o instanceof Location ? (Location) o : ((Block) o).getLocation().add(0.5, 0.5, 0.5);
final Direction d = direction.getSingle(e);
if (d == null)
return null;
if (l.getBlock() == null)
return null;
return new BlockLineIterator(l, o != l ? d.getDirection((Block) o) : d.getDirection(l), SkriptConfig.maxTargetBlockDistance.value());
} else {
final Block b = (Block) from.getSingle(e);
if (b == null)
return null;
assert end != null;
final Block b2 = end.getSingle(e);
if (b2 == null || b2.getWorld() != b.getWorld())
return null;
return new BlockLineIterator(b, b2);
}
} catch (final IllegalStateException ex) {
if (ex.getMessage().equals("Start block missed in BlockIterator"))
return null;
throw ex;
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockChange(EntityChangeBlockEvent event) {
if (physicsFreeze) {
event.setCancelled(true);
return;
}
Block block = event.getBlock();
int x = block.getX();
int z = block.getZ();
int cx = x >> 4;
int cz = z >> 4;
int[] count = getCount(cx, cz);
if (count[1] >= Settings.IMP.TICK_LIMITER.FALLING) {
event.setCancelled(true);
return;
}
if (event.getEntityType() == EntityType.FALLING_BLOCK) {
if (++count[1] >= Settings.IMP.TICK_LIMITER.FALLING) {
// Only cancel falling blocks when it's lagging
if (Fawe.get().getTimer().getTPS() < 18) {
cancelNearby(cx, cz);
if (rateLimit <= 0) {
rateLimit = 20;
Fawe.debug("[FAWE `tick-limiter`] Detected and cancelled falling block lag source at " + block.getLocation());
}
event.setCancelled(true);
return;
} else {
count[1] = 0;
}
}
}
}
@Nullable
final static Block getOnBlock(final Location l) {
Block block = l.getWorld().getBlockAt(l.getBlockX(), (int) (Math.ceil(l.getY()) - 1), l.getBlockZ());
if (block.getType() == Material.AIR && Math.abs((l.getY() - l.getBlockY()) - 0.5) < Skript.EPSILON) { // Fences
block = l.getWorld().getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ());
if (!fencePart.isOfType(block))
return null;
}
return block;
}
/**
* Comes AFTER the SpawnEvents{@link #onCreatureSpawn(CreatureSpawnEvent)} - so cancelled will have effect
* @param e
*/
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onCreatureSpawn(CreatureSpawnEvent e) {
if (!spawnEnabled || e.getSpawnReason() != CreatureSpawnEvent.SpawnReason.NATURAL) {
return;
}
if (!plugin.getWorldManager().isSkyNether(e.getLocation().getWorld())) {
return;
}
if (e.getLocation().getBlockY() > plugin.getWorldManager().getNetherWorld().getMaxHeight()) {
// Block spawning above nether...
e.setCancelled(true);
return;
}
if (e.getEntity() instanceof PigZombie) {
Block block = e.getLocation().getBlock().getRelative(BlockFace.DOWN);
if (isNetherFortressWalkway(block)) {
e.setCancelled(true);
double p = RND.nextDouble();
if (p <= chanceWither && block.getRelative(BlockFace.UP, 3).getType() == Material.AIR) {
WitherSkeleton mob = (WitherSkeleton) e.getLocation().getWorld().spawnEntity(
e.getLocation(), EntityType.WITHER_SKELETON);
mob.getEquipment().setItemInMainHand(new ItemStack(Material.STONE_SWORD, 1));
} else if (p <= chanceWither+chanceBlaze) {
e.getLocation().getWorld().spawnEntity(e.getLocation(), EntityType.BLAZE);
} else if (p <= chanceWither+chanceBlaze+chanceSkeleton) {
e.getLocation().getWorld().spawnEntity(e.getLocation(), EntityType.SKELETON);
} else {
e.setCancelled(false); // Spawn PigZombie
}
}
}
}
@Override
public float getDestroySpeed(Block obbBlock) {
net.minecraft.server.v1_8_R3.Block block =
(net.minecraft.server.v1_8_R3.Block) WrappedBlock.getWrappedBlock(obbBlock, Hawk.getServerVersion()).getNMS();
if(itemStack == null)
return 1F;
return itemStack.a(block);
}
@SuppressWarnings("null")
@Override
protected Block[] get(final Event e) {
final Iterator<Block> iter = iterator(e);
final ArrayList<Block> r = new ArrayList<>();
while (iter.hasNext())
r.add(iter.next());
return r.toArray(new Block[r.size()]);
}
/**
* Remove a list of blocks from the world
*
* @param sender
* @param blocks
*/
private void removeBlocks(CommandSender sender, List<Block> blocks) {
int count = 0;
for (Block block : blocks) {
if (block == null || !isProtectable(block)) {
continue;
}
// possibility of a double chest
if (DoubleChestMatcher.PROTECTABLES_CHESTS.contains(block.getType())) {
Block doubleChest = findAdjacentDoubleChest(block);
if (doubleChest != null) {
removeInventory(doubleChest);
doubleChest.setType(Material.AIR);
}
}
// remove the inventory from the block if it has one
removeInventory(block);
// and now remove the block
block.setType(Material.AIR);
count++;
}
sender.sendMessage("Removed " + count + " blocks from the world");
}
@Override
public BlockUseHandler getItemHandler() {
return e -> {
Optional<Block> block = e.getClickedBlock();
if (block.isPresent()) {
e.cancel();
Player p = e.getPlayer();
Block b = block.get();
if (p.hasPermission("slimefun.inventory.bypass") || SlimefunPlugin.getProtectionManager().hasPermission(p, b.getLocation(), ProtectableAction.ACCESS_INVENTORIES)) {
ItemStack input = e.getItem();
ItemStack output = getOutput(p, input);
if (output != null) {
TaskQueue tasks = new TaskQueue();
tasks.thenRepeatEvery(30, 10, () -> {
Material material = input.getType().isBlock() ? input.getType() : Material.HAY_BLOCK;
b.getWorld().playEffect(b.getLocation(), Effect.STEP_SOUND, material);
});
tasks.thenRun(20, () -> {
p.getWorld().playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1F, 1F);
pushItem(b, output.clone());
});
tasks.execute(SlimefunPlugin.instance);
}
else {
SlimefunPlugin.getLocalization().sendMessage(p, "machines.wrong-item", true);
}
}
}
};
}
@Override
public BlockFace getFacing(Block block) {
if (block.getBlockData() instanceof Directional) {
return ((Directional) block.getBlockData()).getFacing();
} else if (block.getBlockData() instanceof Rotatable) {
return ((Rotatable) block.getBlockData()).getRotation();
} else {
throw new IllegalArgumentException("Block is not Directional or Rotatable");
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onBlockPlace(BlockPlaceEvent e) {
RedProtect.get().logger.debug(LogLevel.DEFAULT, "GlobalListener - Is BlockPlaceEvent event!");
Block b = e.getBlock();
Player p = e.getPlayer();
Material item = e.getItemInHand().getType();
Region r = RedProtect.get().rm.getTopRegion(e.getBlock().getLocation());
if (r != null) {
return;
}
if (!RedProtect.get().getUtil().canBuildNear(p, b.getLocation())) {
e.setCancelled(true);
return;
}
if (item.name().contains("MINECART") || item.name().contains("BOAT")) {
if (!RedProtect.get().config.globalFlagsRoot().worlds.get(p.getWorld().getName()).use_minecart && !p.hasPermission("redprotect.bypass.world")) {
e.setCancelled(true);
RedProtect.get().logger.debug(LogLevel.DEFAULT, "GlobalListener - Can't place minecart/boat!");
}
} else {
if (!bypassBuild(p, b, 1)) {
e.setCancelled(true);
RedProtect.get().logger.debug(LogLevel.DEFAULT, "GlobalListener - Can't Build!");
}
}
}
public static void applyChanges(Block targetBlock, byte newData) {
if (!Reflections.USE_PRE_13_METHODS) {
return;
}
try {
setDataMethod.invoke(targetBlock, newData);
}
catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
FunnyGuilds.getInstance().getPluginLogger().error("Failed to change block data for a block at: " + LocationUtils.toString(targetBlock.getLocation()), ex);
}
}
public void toggleDoor(Block b) {
BlockState state = b.getState();
if (state instanceof Door) {
Door op = (Door) state.getData();
if (!op.isOpen())
op.setOpen(true);
else
op.setOpen(false);
state.setData(op);
state.update();
}
}