下面列出了怎么用org.bukkit.Material的API类实例代码及写法,或者点击链接到github查看源代码。
private void breakLog(Block log, Block android, BlockMenu menu, BlockFace face) {
ItemStack drop = new ItemStack(log.getType());
if (menu.fits(drop, getOutputSlots())) {
menu.pushItem(drop, getOutputSlots());
log.getWorld().playEffect(log.getLocation(), Effect.STEP_SOUND, log.getType());
if (log.getY() == android.getRelative(face).getY()) {
Optional<Material> sapling = MaterialConverter.getSaplingFromLog(log.getType());
if (sapling.isPresent()) {
log.setType(sapling.get());
}
}
else {
log.setType(Material.AIR);
}
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent e) {
if (isActivated(Scenario.CUTCLEAN) || isActivated(Scenario.TRIPLEORES) || isActivated(Scenario.VEINMINER)){
return;
}
Block block = e.getBlock();
Location loc = e.getBlock().getLocation().add(0.5, 0, 0.5);
if (block.getType() == Material.GOLD_ORE){
block.setType(Material.AIR);
loc.getWorld().dropItem(loc,new ItemStack(Material.GOLD_INGOT, 2));
UhcItems.spawnExtraXp(loc,6);
}
}
public static Material changeMaterialColor(Material material, TeamColor teamColor) {
String materialName = material.name();
try {
materialName = material.toString().substring(material.toString().indexOf("_") + 1);
} catch (StringIndexOutOfBoundsException ignored) {
}
String teamMaterialColor = teamColor.material1_13;
if (Main.autoColoredMaterials.contains(materialName)) {
return Material.getMaterial(teamMaterialColor + "_" + materialName);
} else if (material.toString().contains("GLASS")) {
return Material.getMaterial(teamMaterialColor + "_STAINED_GLASS");
} else if (material.toString().contains("GLASS_PANE")) {
return Material.getMaterial(teamMaterialColor + "_STAINED_GLASS_PANE");
}
return material;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInteract(final PlayerInteractEvent event) {
if(cancelUnlessInteracting(event, event.getPlayer())) {
// Allow the how-to book to be read
if(event.getMaterial() == Material.WRITTEN_BOOK) {
event.setUseItemInHand(Event.Result.ALLOW);
} else {
event.setUseItemInHand(Event.Result.DENY);
event.setUseInteractedBlock(Event.Result.DENY);
}
MatchPlayer player = getMatch().getPlayer(event.getPlayer());
if(player == null) return;
if(!player.isSpawned()) {
ClickType clickType = convertClick(event.getAction(), event.getPlayer());
if(clickType == null) return;
getMatch().callEvent(new ObserverInteractEvent(player, clickType, event.getClickedBlock(), null, event.getItem()));
}
// Right-clicking armor will put it on unless we do this
event.getPlayer().updateInventory();
}
}
@EventHandler
public void onTeamChestBuilt(BedwarsPlayerBuildBlock event) {
if (event.isCancelled()) {
return;
}
Block block = event.getBlock();
RunningTeam team = event.getTeam();
if (block.getType() != Material.ENDER_CHEST) {
return;
}
String unhidden = APIUtils.unhashFromInvisibleStringStartsWith(event.getItemInHand(), TEAM_CHEST_PREFIX);
if (unhidden != null || Main.getConfigurator().config.getBoolean("specials.teamchest.turn-all-enderchests-to-teamchests")) {
team.addTeamChest(block);
String message = i18n("team_chest_placed");
for (Player pl : team.getConnectedPlayers()) {
pl.sendMessage(message);
}
}
}
/**
* Add all NBT Data from a Map. The String is the NBT Key, the Object is the
* data you wish to store. Valid types are: Void, byte, short, int, long,
* float, double, byte[], int[], String, List and Map.
*
* @param nbtData
*/
public void addAllNBTData(Map<? extends String, ? extends Object> nbtData) {
if (itemStack == null || itemStack.getType().equals(Material.AIR))
return;
ItemStack stack = NbtFactory.getCraftItemStack(itemStack);
NbtCompound nbt = NbtFactory.fromItemTag(stack);
nbt.putAll(nbtData);
updateLore();
}
@EventHandler(ignoreCancelled = true)
public void onLeftClick(PlayerInteractEvent event) {
if (!(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.LEFT_CLICK_BLOCK)) {
return;
}
ItemStack itemStack = ReflectionUtils.invokeMethod(event.getPlayer(), this.getItemInHandMethod);
if (itemStack != null && itemStack.getType() != Material.AIR) {
NBTItem nbtItem = new NBTItem(itemStack);
if (!nbtItem.hasKey("HubBasics")) return;
event.setCancelled(true);
CustomItem item = HubBasics.getInstance().getItemManager().get(nbtItem.getString("HubBasics"));
if (item == null) {
itemStack.setType(Material.AIR); // Destroy old item
return;
}
if (!item.getRunOnLeftClick()) return;
item.onCommand(event.getPlayer());
}
}
@Override
public void reload() {
FileConfiguration config = getConfig();
config.options().copyDefaults(true);
config.addDefault("Allowed", true);
config.addDefault("Color", "%YELLOW%");
config.addDefault("MaxLevel", 2);
config.addDefault("SlotCost", 1);
config.addDefault("EnchantCost", 10);
config.addDefault("Enchantable", true);
config.addDefault("Recipe.Enabled", false);
ConfigurationManager.saveConfig(config);
ConfigurationManager.loadConfig("Modifiers" + File.separator, getFileName());
init(Material.BLAZE_ROD);
}
@EventHandler(priority = EventPriority.LOW)
public void onInventoryClick(final InventoryClickEvent event)
{
final User user = UserManager.getUser(event.getWhoClicked().getUniqueId());
if (user != null &&
// Quickbar actions can be performed outside the inventory.
event.getSlotType() != InventoryType.SlotType.QUICKBAR)
{
// Only update if the inventory is currently closed to not interfere with opening time checks.
if (!user.hasOpenInventory()) {
user.getTimestampMap().updateTimeStamp(TimestampKey.INVENTORY_OPENED);
}
user.getTimestampMap().updateTimeStamp(TimestampKey.LAST_INVENTORY_CLICK);
if (event.getCurrentItem() != null) {
user.getTimestampMap().updateTimeStamp(TimestampKey.LAST_INVENTORY_CLICK_ON_ITEM);
}
user.getDataMap().setValue(DataKey.LAST_RAW_SLOT_CLICKED, event.getRawSlot());
user.getDataMap().setValue(DataKey.LAST_MATERIAL_CLICKED, event.getCurrentItem() == null ?
Material.AIR :
event.getCurrentItem().getType());
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onInteract(PlayerInteractEvent clickEvent) {
Player player = clickEvent.getPlayer();
PlayerInventory inventory = player.getInventory();
ItemStack mainHandItem;
if (mainHandSupported) {
mainHandItem = inventory.getItemInMainHand();
} else {
mainHandItem = inventory.getItemInHand();
}
if (isOurGraph(mainHandItem)) {
inventory.setItemInMainHand(new ItemStack(Material.AIR));
}
}
@Override
public int spaceForItem(TPDirection insertDirection, ItemStack insertion) {
if (isInvLocked(cachedInvHolder)) {
return 0;
}
int space = 0;
for (int i = 0; i < cachedInv.getSize(); i++) {
ItemStack item = cachedInv.getItem(i);
if (item == null || item.getType() == Material.AIR) {
space += insertion.getMaxStackSize();
} else if (item.isSimilar(insertion) && item.getAmount() < item.getMaxStackSize()) {
space += item.getMaxStackSize() - item.getAmount();
}
}
return space;
}
/**
* Creates a door with a given time in seconds.
*
* @param player the player who is setting the arena up
* @param input the time, in seconds, the door will take to open
*/
private void addDoor(Player player, String input) {
Block block = player.getEyeLocation().getBlock();
Material material = block.getType();
if (material != Material.SIGN_POST && material != Material.WALL_SIGN) {
Messages.BLOCK_NOT_SIGN.send(player);
return;
}
int seconds = Utils.getNumber(player, input);
if (seconds < 0) {
Messages.BAD_SECONDS.send(player);
return;
}
int signID = editedFile.createListLocation(player, block.getLocation(), "Doors");
editedFile.getConfig().set("Doors." + signID + ".Timer", seconds);
editedFile.saveFile();
Messages.CREATED_SIGN.send(player, signID, seconds);
}
private boolean removeSign(CommandSender commandSender, Player player) {
if (checkSignSelectorActive(commandSender)) {
return true;
}
Block block = player.getTargetBlock((Set<Material>) null, 15);
if (block.getState() instanceof org.bukkit.block.Sign) {
if (SignSelector.getInstance().containsPosition(block.getLocation())) {
Sign sign = SignSelector.getInstance().getSignByPosition(block.getLocation());
if (sign != null) {
CloudAPI.getInstance().getNetworkConnection().sendPacket(new PacketOutRemoveSign(sign));
commandSender.sendMessage(CloudAPI.getInstance().getPrefix() + "The sign has been removed");
}
}
}
return false;
}
public InventoryView openEnchanting(Location location, boolean force) {
if (!force) {
Block block = location.getBlock();
if (block.getType() != Material.ENCHANTMENT_TABLE) {
return null;
}
}
if (location == null) {
location = getLocation();
}
getHandle().displayGUIEnchantment(location.getBlockX(), location.getBlockY(), location.getBlockZ(), null);
if (force) {
getHandle().openContainer.checkReachable = false;
}
return getHandle().openContainer.getBukkitView();
}
@Override
public void test() throws Exception {
ItemStack item = new ItemStack(Material.STONE, 1);
ItemMeta meta = item.getItemMeta();
meta.setLore(Lists.newArrayList("Firest Line", "Second Line"));
item.setItemMeta(meta);
String nbt = NBTItem.convertItemtoNBT(item).toString();
if (!nbt.contains("Firest Line") || !nbt.contains("Second Line"))
throw new NbtApiException("The Item nbt '" + nbt + "' didn't contain the lore");
ItemStack rebuild = NBTItem.convertNBTtoItem(new NBTContainer(nbt));
if (!item.isSimilar(rebuild))
throw new NbtApiException("Rebuilt item did not match the original!");
NBTContainer cont = new NBTContainer();
cont.setItemStack("testItem", item);
if(!cont.getItemStack("testItem").isSimilar(item))
throw new NbtApiException("Rebuilt item did not match the original!");
}
@Override
public ItemStack getMaterial(String item) {
if (item.equalsIgnoreCase("SKULL_ITEM")) {
return new ItemStack(Material.SKULL_ITEM, 1, (short) 1);
} else {
return new ItemStack(Material.valueOf(item), 1);
}
}
public FishObjective(Instruction instruction) throws InstructionParseException {
super(instruction);
template = FishData.class;
String[] fishParts = instruction.next().split(":");
fish = Material.matchMaterial(fishParts[0]);
if (fish == null) {
fish = Material.matchMaterial(fishParts[0], true);
if (fish == null) {
throw new InstructionParseException("Unknown fish type");
}
}
if (fishParts.length > 1) {
try {
data = Byte.parseByte(fishParts[1]);
} catch (NumberFormatException e) {
throw new InstructionParseException("Could not parse fish data value", e);
}
} else {
data = -1;
}
amount = instruction.getInt();
if (amount < 1) {
throw new InstructionParseException("Fish amount cannot be less than 0");
}
notifyInterval = instruction.getInt(instruction.getOptional("notify"), 1);
notify = instruction.hasArgument("notify") || notifyInterval > 0;
}
public static GunYML createAndLoadNewGun(String name, String displayname, Material material, int id,
WeaponType type, WeaponSounds sound, boolean hasIronSights, String ammotype, int damage, int maxBullets,
int cost) {
File newGunsDir = new File(QAMain.getInstance().getDataFolder(), "newGuns");
final File gunFile = new File(newGunsDir, name);
new BukkitRunnable() {
public void run() {
GunYMLLoader.loadGuns(QAMain.getInstance(), gunFile);
}
}.runTaskLater(QAMain.getInstance(), 1);
return GunYMLCreator.createNewCustomGun(QAMain.getInstance().getDataFolder(), name, name, displayname, id, null,
type, sound, hasIronSights, ammotype, damage, maxBullets, cost).setMaterial(material);
}
/**
* Adds a block to the block cache by its Block name, and tries to add it if it doesn't exist.
*
* @param block
*/
public int addBlock(String block) {
Material material = Material.matchMaterial(block);
if (material != null) {
return addBlock(material);
}
return -1;
}
@Test
public void testBackpackDropNormalItem() throws InterruptedException {
Player player = server.addPlayer();
openMockBackpack(player, "DROP_NORMAL_ITEM_BACKPACK_TEST", 27);
Item item = Mockito.mock(Item.class);
Mockito.when(item.getItemStack()).thenReturn(new ItemStack(Material.SUGAR_CANE));
PlayerDropItemEvent event = new PlayerDropItemEvent(player, item);
listener.onItemDrop(event);
Assertions.assertFalse(event.isCancelled());
}
public static void removeRecipe(Material type, short durability) {
Iterator<Recipe> recipes = Bukkit.recipeIterator();
Recipe recipe;
while (recipes.hasNext()) {
recipe = recipes.next();
if (recipe != null && recipe.getResult().getType() == type && recipe.getResult().getDurability() == durability) {
recipes.remove();
}
}
}
public CItem(String originalName, ChatColor color, String lDescription, long lCooldown, Material mat) {
this.typeString = "Items";
this.itemMaterial = mat;
this.originalName = originalName;
this.permissionName = originalName.replace(" ", "").replace("'", "");
this.description = new ArrayList<String>(Arrays.asList(lDescription.split(";")));
this.configEntries.put("Enabled", true);
this.configEntries.put("DisplayName", originalName);
this.configEntries.put("Color", color.name());
this.configEntries.put("Description", lDescription);
this.configEntries.put("Cooldown", lCooldown);
this.configEntries.put("Cost", 0);
}
/**
* Deletes the shop from the list of shops and queues it for database deletion
*
* @param memoryOnly whether to delete from database
*/
@Override
public void delete(boolean memoryOnly) {
this.lastChangedAt = System.currentTimeMillis();
ShopDeleteEvent shopDeleteEvent = new ShopDeleteEvent(this, memoryOnly);
if (Util.fireCancellableEvent(shopDeleteEvent)) {
Util.debugLog("Shop deletion was canceled because a plugin canceled it.");
return;
}
isDeleted = true;
// Unload the shop
if (isLoaded) {
this.onUnload();
}
// Delete the signs around it
for (Sign s : this.getSigns()) {
s.getBlock().setType(Material.AIR);
}
// Delete it from the database
// Refund if necessary
if (plugin.getConfig().getBoolean("shop.refund")) {
plugin.getEconomy().deposit(this.getOwner(), plugin.getConfig().getDouble("shop.cost"));
}
if (memoryOnly) {
// Delete it from memory
plugin.getShopManager().removeShop(this);
} else {
plugin.getShopManager().removeShop(this);
plugin.getDatabaseHelper().removeShop(this);
}
}
@Override
public BehaviourItem[] getDefaultMovementBehaviours() {
return new BehaviourItem[]{
new BehaviourItem(1, new BehaviourFloat(this)),
new BehaviourItem(2, new BehaviourSit(this)),
new BehaviourItem(3, new BehaviourLeapAtTarget(this, 0.4F)),
new BehaviourItem(4, new BehaviourMeleeAttack(this, true, 1.0D)),
new BehaviourItem(5, new BehaviourFollowTamer(this, 10.0F, 2.0F, 1.0D)),
new BehaviourItem(6, new BehaviourBreed(this, 1.0D)),
new BehaviourItem(7, new BehaviourRandomStroll(this, 1.0D)),
new BehaviourItem(8, new BehaviourBeg(this, new Material[]{Material.BONE})),
new BehaviourItem(9, new BehaviourLookAtNearestEntity(this, HumanEntity.class, 8.0F)),
new BehaviourItem(9, new BehaviourLookAtRandom(this))
};
}
public IndustrialMiner(Category category, SlimefunItemStack item, Material baseMaterial, boolean silkTouch, int range) {
super(category, item, new ItemStack[] { null, null, null, new CustomItem(Material.PISTON, "Piston (facing up)"), new ItemStack(Material.CHEST), new CustomItem(Material.PISTON, "Piston (facing up)"), new ItemStack(baseMaterial), new ItemStack(SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_14) ? Material.BLAST_FURNACE : Material.FURNACE), new ItemStack(baseMaterial) }, new ItemStack[0], BlockFace.UP);
this.range = range;
this.silkTouch = silkTouch;
registerDefaultFuelTypes();
}
private static ItemStack getSkull(String id, String texture) {
if (SlimefunPlugin.getMinecraftVersion() == MinecraftVersion.UNIT_TEST) {
return new ItemStack(Material.PLAYER_HEAD);
}
return SkullItem.fromBase64(getTexture(id, texture));
}
@Override
public boolean checkMaterial(FallingBlock fb, Material mat) {
if (fb.getMaterial().equals(mat)) {
return true;
}
return false;
}
/**
* Returns whether the NPC can take durability from the held item.
*/
public boolean shouldTakeDura() {
ItemStack it = getHeldItem();
if (it == null) {
return false;
}
Material type = it.getType();
return SentinelVersionCompat.BOW_MATERIALS.contains(type) || SentinelVersionCompat.SWORD_MATERIALS.contains(type)
|| SentinelVersionCompat.PICKAXE_MATERIALS.contains(type) || SentinelVersionCompat.AXE_MATERIALS.contains(type);
}
private void checkSuccess() {
new BukkitRunnable() {
@Override
public void run() {
if (ent.getLocation().getBlockY() == prevY && !success) {
ent.getWorld().getBlockAt(ent.getLocation()).setType(Material.ENDER_CHEST);
setLocation(ent.getWorld().getBlockAt(ent.getLocation()));
ent.remove();
} else {
prevY = ent.getLocation().getY();
checkSuccess();
}
}
}.runTaskLater(SkyWarsReloaded.get(), 10L);
}
@Test
public void testSetSoulbound() {
ItemStack item = new CustomItem(Material.DIAMOND, "&cI wanna be soulbound!");
Assertions.assertFalse(SlimefunUtils.isSoulbound(item));
SlimefunUtils.setSoulbound(item, true);
Assertions.assertTrue(SlimefunUtils.isSoulbound(item));
Assertions.assertEquals(1, item.getItemMeta().getLore().size());
SlimefunUtils.setSoulbound(item, false);
Assertions.assertFalse(SlimefunUtils.isSoulbound(item));
Assertions.assertEquals(0, item.getItemMeta().getLore().size());
}