下面列出了org.bukkit.inventory.DoubleChestInventory#org.bukkit.block.Chest 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Return a predicate that applies a Filter to the given InventoryHolder,
* or null if the InventoryHolder is not something that we should be filling.
*/
private static @Nullable Predicate<Filter> passesFilter(InventoryHolder holder) {
if(holder instanceof DoubleChest) {
final DoubleChest doubleChest = (DoubleChest) holder;
return filter -> !filter.denies((Chest) doubleChest.getLeftSide()) ||
!filter.denies((Chest) doubleChest.getRightSide());
} else if(holder instanceof BlockState) {
return filter -> !filter.denies((BlockState) holder);
} else if(holder instanceof Player) {
// This happens with crafting inventories, and possibly other transient inventory types
// Pretty sure we never want to fill an inventory held by the player
return null;
} else if(holder instanceof Entity) {
return filter -> !filter.denies(new EntityQuery((Entity) holder));
} else {
// If we're not sure what it is, don't fill it
return null;
}
}
@Test
@Ignore // TODO fix this
public void regionShouldRunUpkeep() {
loadRegionTypeCobble4();
HashMap<UUID, String> owners = new HashMap<>();
owners.put(new UUID(1, 4), Constants.OWNER);
Location location1 = new Location(Bukkit.getWorld("world"), 3, 100, 0);
Region region = new Region("cobble", owners, location1, getRadii(), new HashMap<>(),0);
RegionManager.getInstance().addRegion(region);
Chest chest = (Chest) location1.getBlock().getState();
chest.getBlockInventory().clear();
chest.getBlockInventory().setItem(0, new ItemStackImpl(Material.IRON_PICKAXE, 1));
assertTrue(region.runUpkeep());
assertEquals(Material.GOLDEN_PICKAXE, chest.getBlockInventory().getContents()[0].getType());
chest.getBlockInventory().setItem(0, TestUtil.mockItemStack(Material.IRON_PICKAXE, 1, null, new ArrayList<>()));
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void checkWorth(InventoryOpenEvent event) {
// Do nothing if a player did not open the inventory or if chest events
// are disabled.
if (!(event.getPlayer() instanceof Player) || plugin.getSettings().isDisableChestEvents()) {
return;
}
Inventory inventory = event.getInventory();
// Set all default worth values for this chest.
if (inventory.getHolder() instanceof DoubleChest) {
DoubleChest chest = (DoubleChest) inventory.getHolder();
checkWorth((Chest) chest.getLeftSide());
checkWorth((Chest) chest.getRightSide());
}
if (inventory.getHolder() instanceof Chest) {
checkWorth((Chest) inventory.getHolder());
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void updateWorth(InventoryCloseEvent event) {
// Do nothing if a player did not close the inventory or if chest
// events are disabled.
if (!(event.getPlayer() instanceof Player) || plugin.getSettings().isDisableChestEvents()) {
return;
}
// Get cached values from when chest was opened and add the difference
// to the worth manager.
if (event.getInventory().getHolder() instanceof DoubleChest) {
DoubleChest chest = (DoubleChest) event.getInventory().getHolder();
updateWorth((Chest) chest.getLeftSide());
updateWorth((Chest) chest.getRightSide());
}
if (event.getInventory().getHolder() instanceof Chest) {
updateWorth((Chest) event.getInventory().getHolder());
}
}
public void createMailbox(Player admin, OfflinePlayer player) {
UUID id = player.getUniqueId();
if (plugin.cfg.mailbox.getMailboxLocation(id) != null) {
msg(admin, "user.mailbox.admin.already_set");
return;
}
plugin.mailboxListener.registerRightClickCallback(admin, 100,
(Location clickedBlock) -> {
Block b = clickedBlock.getBlock();
if (b.getState() instanceof Chest) {
plugin.cfg.mailbox.updateNameMapping(id, player.getName());
plugin.cfg.mailbox.updateLocationMapping(id, b.getLocation());
msg(admin, "user.mailbox.admin.success_set");
if (player.isOnline()) {
Player tmp = plugin.getServer().getPlayer(id);
if (tmp != null) {
msg(tmp, "user.mailbox.admin.player_hint_set");
}
}
return;
}
msg(admin, "user.mailbox.admin.fail_set");
});
msg(admin, "user.mailbox.admin.right_click_set", player);
}
/**
* Gets the single block inventory for a potentially double chest.
* Handles people who have an old version of Bukkit.
* This should be replaced with {@link org.bukkit.block.Chest#getBlockInventory()}
* in a few months (now = March 2012) // note from future dev - lol
*
* @param chest The chest to get a single block inventory for
* @return The chest's inventory
*/
private Inventory getBlockInventory(Chest chest) {
try {
return chest.getBlockInventory();
} catch (Throwable t) {
if (chest.getInventory() instanceof DoubleChestInventory) {
DoubleChestInventory inven = (DoubleChestInventory) chest.getInventory();
if (inven.getLeftSide().getHolder().equals(chest)) {
return inven.getLeftSide();
} else if (inven.getRightSide().getHolder().equals(chest)) {
return inven.getRightSide();
} else {
return inven;
}
} else {
return chest.getInventory();
}
}
}
@Override
public boolean clearContainerBlockContents(Vector pt) {
Block block = getWorld().getBlockAt(pt.getBlockX(), pt.getBlockY(), pt.getBlockZ());
if (block == null) {
return false;
}
BlockState state = block.getState();
if (!(state instanceof org.bukkit.inventory.InventoryHolder)) {
return false;
}
org.bukkit.inventory.InventoryHolder chest = (org.bukkit.inventory.InventoryHolder) state;
Inventory inven = chest.getInventory();
if (chest instanceof Chest) {
inven = getBlockInventory((Chest) chest);
}
inven.clear();
return true;
}
public void addChest(Chest chest, ChestPlacementType cpt) {
ArrayList<CoordLoc> list;
if (cpt == ChestPlacementType.NORMAL) {
list = chests;
} else {
list = centerChests;
}
InventoryHolder ih = chest.getInventory().getHolder();
if (ih instanceof DoubleChest) {
DoubleChest dc = (DoubleChest) ih;
Chest left = (Chest) dc.getLeftSide();
Chest right = (Chest) dc.getRightSide();
CoordLoc locLeft = new CoordLoc(left.getX(), left.getY(), left.getZ());
CoordLoc locRight = new CoordLoc(right.getX(), right.getY(), right.getZ());
if (!(list.contains(locLeft) || list.contains(locRight))) {
addChest(locLeft, cpt, true);
}
} else {
CoordLoc loc = new CoordLoc(chest.getX(), chest.getY(), chest.getZ());
if (!list.contains(loc)){
addChest(loc, cpt, true);
}
}
}
public void removeChest(Chest chest) {
InventoryHolder ih = chest.getInventory().getHolder();
if (ih instanceof DoubleChest) {
DoubleChest dc = (DoubleChest) ih;
Chest left = (Chest) dc.getLeftSide();
Chest right = (Chest) dc.getRightSide();
CoordLoc locLeft = new CoordLoc(left.getX(), left.getY(), left.getZ());
CoordLoc locRight = new CoordLoc(right.getX(), right.getY(), right.getZ());
chests.remove(locLeft);
centerChests.remove(locLeft);
chests.remove(locRight);
centerChests.remove(locLeft);
saveArenaData();
} else {
CoordLoc loc = new CoordLoc(chest.getX(), chest.getY(), chest.getZ());
chests.remove(loc);
centerChests.remove(loc);
saveArenaData();
}
}
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true)
public void onItemMove(InventoryMoveItemEvent e) {
if ((e.getSource().getType().equals(InventoryType.CHEST)) && (!e.getInitiator().getType().equals(InventoryType.PLAYER))) {
if (e.getSource().getHolder() instanceof DoubleChest) {
DoubleChest dc = (DoubleChest) e.getSource().getHolder();
Chest r = (Chest) dc.getRightSide();
Chest l = (Chest) dc.getLeftSide();
if (shopUtils.isShop(r.getLocation()) || shopUtils.isShop(l.getLocation())) e.setCancelled(true);
} else if (e.getSource().getHolder() instanceof Chest) {
Chest c = (Chest) e.getSource().getHolder();
if (shopUtils.isShop(c.getLocation())) e.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onInventoryUpdate(InventoryMoveItemEvent e) {
if (!plugin.getHologramFormat().isDynamic()) return;
Location loc = null;
if (e.getSource().getHolder() instanceof Chest) {
loc = ((Chest) e.getSource().getHolder()).getLocation();
} else if (e.getSource().getHolder() instanceof DoubleChest) {
loc = ((DoubleChest) e.getSource().getHolder()).getLocation();
} else if (e.getDestination().getHolder() instanceof Chest) {
loc = ((Chest) e.getDestination().getHolder()).getLocation();
} else if (e.getDestination().getHolder() instanceof DoubleChest) {
loc = ((DoubleChest) e.getDestination().getHolder()).getLocation();
}
if (loc != null) {
Shop shop = plugin.getShopUtils().getShop(loc);
if (shop != null) shop.updateHologramText();
}
}
/**
* Fill the {@link Inventory} of the given chest {@link Location} with the starter and {@link Perk} based items.
* @param chestLocation Location of the chest block.
* @param perk Perk containing extra perk-based items to add.
* @return True if the chest is found and filled, false otherwise.
*/
public boolean setChest(@Nullable Location chestLocation, @NotNull Perk perk) {
if (chestLocation == null || chestLocation.getWorld() == null) {
return false;
}
final Block block = chestLocation.getWorld().getBlockAt(chestLocation);
if (block.getType() == Material.CHEST) {
final Chest chest = (Chest) block.getState();
final Inventory inventory = chest.getInventory();
inventory.addItem(Settings.island_chestItems);
if (Settings.island_addExtraItems) {
inventory.addItem(ItemStackUtil.createItemArray(perk.getExtraItems()));
}
return true;
}
return false;
}
void addSign(Sign block, String[] lines, Chest chest) {
Location loc = block.getLocation();
ConfigurationSection signs = config.getConfigurationSection("signs");
if (signs == null) {
signs = config.createSection("signs");
}
String signLocation = LocationUtil.asKey(loc);
ConfigurationSection signSection = signs.createSection(signLocation);
signSection.set("location", LocationUtil.asString(loc));
signSection.set("challenge", lines[1]);
String chestLocation = LocationUtil.asString(chest.getLocation());
signSection.set("chest", chestLocation);
ConfigurationSection chests = config.getConfigurationSection("chests");
if (chests == null) {
chests = config.createSection("chests");
}
String chestPath = LocationUtil.asKey(chest.getLocation());
List<String> signList = chests.getStringList(chestPath);
if (!signList.contains(signLocation)) {
signList.add(signLocation);
}
chests.set(chestPath, signList);
saveAsync();
updateSignsOnContainer(chest.getLocation());
}
@EventHandler(priority = EventPriority.MONITOR)
public void onSignChanged(SignChangeEvent e) {
if (e.isCancelled() || e.getPlayer() == null
|| !plugin.getWorldManager().isSkyAssociatedWorld(e.getPlayer().getWorld())
|| !e.getLines()[0].equalsIgnoreCase("[usb]")
|| e.getLines()[1].trim().isEmpty()
|| !e.getPlayer().hasPermission("usb.island.signs.place")
|| !(e.getBlock().getType() == SkyBlockMenu.WALL_SIGN_MATERIAL)
|| !(e.getBlock().getState() instanceof Sign)
) {
return;
}
Sign sign = (Sign) e.getBlock().getState();
if(sign.getBlock().getState().getBlockData() instanceof WallSign) {
WallSign data = (WallSign) sign.getBlock().getState().getBlockData();
BlockFace attached = data.getFacing().getOppositeFace();
Block wallBlock = sign.getBlock().getRelative(attached);
if (isChest(wallBlock)) {
logic.addSign(sign, e.getLines(), (Chest) wallBlock.getState());
}
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onInventoryOpenEvent(InventoryOpenEvent event) {
if (event.getInventory() instanceof DoubleChestInventory) {
DoubleChestInventory doubleInv = (DoubleChestInventory)event.getInventory();
Chest leftChest = (Chest)doubleInv.getHolder().getLeftSide();
/*Generate a new player 'switch' event for the left and right chests. */
PlayerInteractEvent interactLeft = new PlayerInteractEvent((Player)event.getPlayer(), Action.RIGHT_CLICK_BLOCK, null, leftChest.getBlock(), null);
BlockListener.OnPlayerSwitchEvent(interactLeft);
if (interactLeft.isCancelled()) {
event.setCancelled(true);
return;
}
Chest rightChest = (Chest)doubleInv.getHolder().getRightSide();
PlayerInteractEvent interactRight = new PlayerInteractEvent((Player)event.getPlayer(), Action.RIGHT_CLICK_BLOCK, null, rightChest.getBlock(), null);
BlockListener.OnPlayerSwitchEvent(interactRight);
if (interactRight.isCancelled()) {
event.setCancelled(true);
return;
}
}
}
public InventoryHolder getHolder() throws CivException {
if (playerName != null) {
Player player = CivGlobal.getPlayer(playerName);
return (InventoryHolder)player;
}
if (blockLocation != null) {
/* Make sure the chunk is loaded. */
if (!blockLocation.getChunk().isLoaded()) {
if(!blockLocation.getChunk().load()) {
throw new CivException("Couldn't load chunk at "+blockLocation+" where holder should reside.");
}
}
if (!(blockLocation.getBlock().getState() instanceof Chest)) {
throw new CivException("Holder location is not a chest, invalid.");
}
Chest chest = (Chest) blockLocation.getBlock().getState();
return chest.getInventory().getHolder();
}
throw new CivException("Invalid holder.");
}
public void setHolder(InventoryHolder holder) throws CivException {
if (holder instanceof Player) {
Player player = (Player)holder;
playerName = player.getName();
blockLocation = null;
return;
}
if (holder instanceof Chest) {
Chest chest = (Chest)holder;
playerName = null;
blockLocation = chest.getLocation();
return;
}
if (holder instanceof DoubleChest) {
DoubleChest dchest = (DoubleChest)holder;
playerName = null;
blockLocation = dchest.getLocation();
return;
}
throw new CivException("Invalid holder passed to set holder:"+holder.toString());
}
public void setHolder(InventoryHolder holder) throws CivException {
if (holder == null) {
return;
}
if (holderStore == null) {
if (holder instanceof Chest) {
holderStore = new InventoryHolderStorage(((Chest)holder).getLocation());
} else if (holder instanceof Player){
holderStore = new InventoryHolderStorage((Player)holder);
} else {
throw new CivException("Invalid holder.");
}
} else {
holderStore.setHolder(holder);
}
// If we have a holder, we cannot be on the ground or in a item frame.
this.frameStore = null;
this.item = null;
}
private Optional<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 Optional.of(inv);
}
}
}
}
return Optional.empty();
}
/**
* This consumes fuel from the given {@link Chest}.
*
* @return The gained fuel value
*/
private int consumeFuel() {
if (chest.getType() == Material.CHEST) {
Inventory inv = ((Chest) chest.getState()).getBlockInventory();
for (int i = 0; i < inv.getSize(); i++) {
for (MachineFuel fuelType : miner.fuelTypes) {
ItemStack item = inv.getContents()[i];
if (fuelType.test(item)) {
ItemUtils.consumeItem(item, false);
if (miner instanceof AdvancedIndustrialMiner) {
inv.addItem(new ItemStack(Material.BUCKET));
}
return fuelType.getTicks();
}
}
}
}
return 0;
}
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;
}
protected int getCurrencyInChest() {
int total = 0;
Block chest = this.getChest();
if (Utils.isChest(chest.getType())) {
Inventory inv = ((Chest) chest.getState()).getInventory();
ItemStack[] contents = inv.getContents();
for (ItemStack item : contents) {
if (Settings.isCurrencyItem(item)) {
total += item.getAmount();
} else if (Settings.isHighCurrencyItem(item)) {
total += item.getAmount() * Settings.highCurrencyValue;
}
}
}
return total;
}
private void spawnChest(){
spawned = true;
block1 = loc.getBlock();
loc.add(-1, 0, 0);
block2 = loc.getBlock();
block1.setType(Material.CHEST);
block2.setType(Material.CHEST);
Chest chest1 = (Chest) block1.getState();
Chest chest2 = (Chest) block2.getState();
String chestName = Lang.SCENARIO_TIMEBOMB_CHEST.replace("%player%", name);
VersionUtils.getVersionUtils().setChestName(chest1, chestName);
VersionUtils.getVersionUtils().setChestName(chest2, chestName);
// Make double chest for 1.13 and up
VersionUtils.getVersionUtils().setChestSide(chest1, false);
VersionUtils.getVersionUtils().setChestSide(chest2, true);
Inventory inv = chest1.getInventory();
for (ItemStack drop : drops){
inv.addItem(drop);
}
loc.add(1,-1,.5);
armorStand = (ArmorStand) loc.getWorld().spawnEntity(loc, EntityType.ARMOR_STAND);
armorStand.setCustomNameVisible(true);
armorStand.setGravity(false);
armorStand.setVisible(false);
armorStand.setCustomName("");
}
@Override
public void setChestSide(Chest chest, boolean left){
org.bukkit.block.data.type.Chest chestData = (org.bukkit.block.data.type.Chest) chest.getBlockData();
org.bukkit.block.data.type.Chest.Type side = left ? org.bukkit.block.data.type.Chest.Type.LEFT : org.bukkit.block.data.type.Chest.Type.RIGHT;
chestData.setType(side);
chest.getBlock().setBlockData(chestData, true);
}
@Override
public void setChestName(Chest chest, String name){
try {
Class craftChest = NMSUtils.getNMSClass("block.CraftChest");
Method getTileEntity = NMSUtils.getMethod(craftChest, "getTileEntity");
Object tileChest = getTileEntity.invoke(chest);
Method a = NMSUtils.getMethod(tileChest.getClass(), "a", String.class);
a.invoke(tileChest, name);
}catch (Exception ex){ // todo find a way to change the chest name on other versions up to 1.11
Bukkit.getLogger().severe("[UhcCore] Failed to rename chest! Are you on 1.9-1.11?");
ex.printStackTrace();
}
}
public void removeRegion(Region region, boolean broadcast, boolean checkCritReqs) {
if (broadcast) {
RegionType regionType = (RegionType) ItemManager.getInstance().getItemType(region.getType());
runRegionCommands(region, regionType.getCommandsOnDestruction());
broadcastRegionDestroyed(region);
}
for (Map.Entry<String, DestroyRegionListener> entry : this.destroyRegionListener.entrySet()) {
entry.getValue().destroyRegionHandler(region);
}
Bukkit.getPluginManager().callEvent(new RegionDestroyedEvent(region));
if (checkCritReqs) {
TownManager.getInstance().checkCriticalRequirements(region);
}
Block block = region.getLocation().getBlock();
if (block instanceof Chest) {
ItemStack[] contents = ((Chest) block).getBlockInventory().getContents();
for (ItemStack is : contents) {
if (is != null) {
block.getWorld().dropItemNaturally(block.getLocation(), is);
}
}
((Chest) block).getBlockInventory().clear();
}
if (Civs.getInstance() != null) {
region.getLocation().getBlock().setType(Material.AIR);
}
BlockLogger.getInstance().removeBlock(region.getLocation());
removeRegion(region);
}
@EventHandler(ignoreCancelled = true)
public void onCivilianDragItem(InventoryDragEvent event) {
if (event.getView().getTopInventory().getHolder() instanceof Chest) {
Location inventoryLocation = ((Chest) event.getView().getTopInventory().getHolder()).getLocation();
UnloadedInventoryHandler.getInstance().updateInventoryAtLocation(inventoryLocation);
}
if (ConfigManager.getInstance().getAllowSharingCivsItems()) {
return;
}
ItemStack dragged = event.getOldCursor();
if (!CVItem.isCivsItem(dragged) ||
MenuManager.getInstance().hasMenuOpen(event.getWhoClicked().getUniqueId())) {
return;
}
int inventorySize = event.getInventory().getSize();
for (int i : event.getRawSlots()) {
if (i < inventorySize) {
event.setCancelled(true);
HumanEntity humanEntity = event.getWhoClicked();
humanEntity.sendMessage(Civs.getPrefix() +
LocaleManager.getInstance().getTranslationWithPlaceholders((Player) humanEntity, LocaleConstants.PREVENT_CIVS_ITEM_SHARE));
return;
}
}
}
public void setInventory() {
Block block = this.location.getBlock();
if (block.getType() != Material.CHEST) {
this.valid = false;
return;
}
try {
Chest chest = (Chest) block.getState();
this.inventory = chest.getInventory();
this.size = this.inventory.getSize();
} catch (Exception e) {
this.valid = false;
}
}
public static Block createUniqueBlock(Material mat, String name, Location location, boolean containsPickaxe) {
Block block = new BlockImpl(location);
block.setType(mat);
if (containsPickaxe) {
((Chest) block.getState()).getBlockInventory()
.addItem(mockItemStack(Material.IRON_PICKAXE, 1, null, new ArrayList<>()));
}
return block;
}
private void updateWorth(Chest chest) {
if (chest == null) return;
BlockPos pos = BlockPos.of(chest.getBlock());
ChestWorth worth = chests.remove(pos);
if (worth == null) return;
worth = getDifference(worth, getWorth(chest.getBlockInventory()));
plugin.getWorthManager().add(chest.getChunk(), RecalculateReason.CHEST, WorthType.CHEST,
worth.getTotalWorth(), worth.getMaterials(), worth.getSpawners());
}