org.bukkit.block.Chest Java Examples

The following examples show how to use org.bukkit.block.Chest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GameMap.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
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();
	}

}
 
Example #2
Source File: BonusGoodie.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
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;
	
}
 
Example #3
Source File: InventoryHolderStorage.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
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());
}
 
Example #4
Source File: InventoryHolderStorage.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
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.");
}
 
Example #5
Source File: Composter.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
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();
}
 
Example #6
Source File: PlayerListener.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
@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;
		}			
	}
}
 
Example #7
Source File: MultiBlockMachine.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: PlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: FillListener.java    From ProjectAres with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example #10
Source File: ActiveMiner.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #11
Source File: SignEvents.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
@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());
        }
    }
}
 
Example #12
Source File: SignLogic.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
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());
}
 
Example #13
Source File: IslandGenerator.java    From uSkyBlock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #14
Source File: GameMap.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
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);
           }
       }
}
 
Example #15
Source File: BukkitWorld.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
@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;
}
 
Example #16
Source File: BukkitWorld.java    From FastAsyncWorldedit with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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();
        }
    }
}
 
Example #17
Source File: ChestProtectListener.java    From ShopChest with MIT License 6 votes vote down vote up
@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);
        }
    }
}
 
Example #18
Source File: MailboxCommands.java    From NyaaUtils with MIT License 6 votes vote down vote up
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);
}
 
Example #19
Source File: ShopUpdateListener.java    From ShopChest with MIT License 6 votes vote down vote up
@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();
    }
}
 
Example #20
Source File: WorthListener.java    From factions-top with MIT License 6 votes vote down vote up
@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());
    }
}
 
Example #21
Source File: WorthListener.java    From factions-top with MIT License 6 votes vote down vote up
@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());
    }
}
 
Example #22
Source File: RegionsTests.java    From Civs with GNU General Public License v3.0 6 votes vote down vote up
@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<>()));
}
 
Example #23
Source File: ShopUtils.java    From ShopChest with MIT License 5 votes vote down vote up
/**
 * Add a shop
 * @param shop Shop to add
 * @param addToDatabase Whether the shop should also be added to the database
 * @param callback Callback that - if succeeded - returns the ID the shop had or was given (as {@code int})
 */
public void addShop(Shop shop, boolean addToDatabase, Callback<Integer> callback) {
    InventoryHolder ih = shop.getInventoryHolder();
    plugin.debug("Adding shop... (#" + shop.getID() + ")");

    if (ih instanceof DoubleChest) {
        DoubleChest dc = (DoubleChest) ih;
        Chest r = (Chest) dc.getRightSide();
        Chest l = (Chest) dc.getLeftSide();

        plugin.debug("Added shop as double chest. (#" + shop.getID() + ")");

        shopLocation.put(r.getLocation(), shop);
        shopLocation.put(l.getLocation(), shop);
    } else {
        plugin.debug("Added shop as single chest. (#" + shop.getID() + ")");

        shopLocation.put(shop.getLocation(), shop);
    }

    if (addToDatabase) {
        if (shop.getShopType() != ShopType.ADMIN) {
            playerShopAmount.compute(shop.getVendor().getUniqueId(), (uuid, amount) -> amount == null ? new Counter(1) : amount.increment());
        }
        plugin.getShopDatabase().addShop(shop, callback);
    } else {
        if (callback != null) callback.callSyncResult(shop.getID());
    }

}
 
Example #24
Source File: Utils.java    From ShopChest with MIT License 5 votes vote down vote up
/**
 * Get a set for the location(s) of the shop's chest(s)
 * @param shop The shop
 * @return A set of 1 or 2 locations
 */
public static Set<Location> getChestLocations(Shop shop) {
    Set<Location> chestLocations = new HashSet<>();
    InventoryHolder ih = shop.getInventoryHolder();
    if (ih instanceof DoubleChest) {
        DoubleChest dc = (DoubleChest) ih;
        chestLocations.add(((Chest) dc.getLeftSide()).getLocation());
        chestLocations.add(((Chest) dc.getRightSide()).getLocation());
    } else {
        chestLocations.add(shop.getLocation());
    }
    return chestLocations;
}
 
Example #25
Source File: ShopUtils.java    From ShopChest with MIT License 5 votes vote down vote up
/** Remove a shop. May not work properly if double chest doesn't exist!
 * @param shop Shop to remove
 * @param removeFromDatabase Whether the shop should also be removed from the database
 * @param callback Callback that - if succeeded - returns null
 * @see ShopUtils#removeShopById(int, boolean, Callback)
 */
public void removeShop(Shop shop, boolean removeFromDatabase, Callback<Void> callback) {
    plugin.debug("Removing shop (#" + shop.getID() + ")");

    if (shop.isCreated()) {
        InventoryHolder ih = shop.getInventoryHolder();

        if (ih instanceof DoubleChest) {
            DoubleChest dc = (DoubleChest) ih;
            Chest r = (Chest) dc.getRightSide();
            Chest l = (Chest) dc.getLeftSide();

            shopLocation.remove(r.getLocation());
            shopLocation.remove(l.getLocation());
        } else {
            shopLocation.remove(shop.getLocation());
        }

        shop.removeItem();
        shop.removeHologram();
    }

    if (removeFromDatabase) {
        if (shop.getShopType() != ShopType.ADMIN) {
            playerShopAmount.compute(shop.getVendor().getUniqueId(), (uuid, amount) -> amount == null ? new Counter() : amount.decrement());
        }
        plugin.getShopDatabase().removeShop(shop, callback);
    } else {
        if (callback != null) callback.callSyncResult(null);
    }
}
 
Example #26
Source File: ChestManager.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
private void fillChest(Object chest, Map<Integer, Inventory> fill) {
	Inventory inventory = null;
	if (chest instanceof Chest) {
		inventory = ((Chest) chest).getInventory();
	} else if (chest instanceof DoubleChest) {
		inventory = ((DoubleChest) chest).getInventory();
	}
	if (inventory != null) {
		inventory.clear();
		int added = 0;
		Collections.shuffle(randomLoc);
		Collections.shuffle(randomDLoc);
		for (int chance: fill.keySet()) {
			for (ItemStack item: fill.get(chance)) {
				if (item != null && !item.getType().equals(Material.AIR)) {
					if (chest instanceof Chest) {
						if (random.nextInt(100) + 1 <= chance) {
							inventory.setItem(randomLoc.get(added), item);
							added++;
							if (added >= inventory.getSize() - 1 || added >= SkyWarsReloaded.getCfg().getMaxChest()) {
								break;
							}
						}
					}
					if (chest instanceof DoubleChest) {
						if (random.nextInt(100) + 1 <= chance) {
							inventory.setItem(randomDLoc.get(added), item);
							added++;
							if (added >= inventory.getSize() - 1 || added >= SkyWarsReloaded.getCfg().getMaxDoubleChest()) {
								break;
							}
						}
					}
				}
			}
		}
	}
}
 
Example #27
Source File: WarRegen.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
public static void destroyThisBlock(Block blk, Town town) {
	
	WarRegen.saveBlock(blk, town.getName(), false);
			
	switch (blk.getType()) {
	case TRAPPED_CHEST:
		((Chest)blk.getState()).getBlockInventory().clear();
		break;
	case CHEST:
		((Chest)blk.getState()).getBlockInventory().clear();
		break;
	case DISPENSER:
		((Dispenser)blk.getState()).getInventory().clear();
		break;
	case BURNING_FURNACE:
	case FURNACE:
		((Furnace)blk.getState()).getInventory().clear();
		break;
	case DROPPER:
		((Dropper)blk.getState()).getInventory().clear();
		break;
	case HOPPER:
		((Hopper)blk.getState()).getInventory().clear();
		break;
	default:
		break;
	}
	
	ItemManager.setTypeId(blk, CivData.AIR);
	ItemManager.setData(blk, 0x0, true);
	
}
 
Example #28
Source File: PlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
protected List<ItemCount> getItemsFromChest(Filter<ItemStack> filter) {
	Inventory chestInventory = null;
	Block chest = this.getChest();
	if (Utils.isChest(chest.getType())) {
		chestInventory = ((Chest) chest.getState()).getInventory();
	}
	return Utils.getItemCountsFromInventory(chestInventory, filter);
}
 
Example #29
Source File: PlayerShopkeeper.java    From Shopkeepers with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean openChestWindow(Player player) {
	Log.debug("checking open chest window ..");
	// make sure the chest still exists
	Block chest = this.getChest();
	if (Utils.isChest(chest.getType())) {
		// open the chest directly as the player (no need for a custom UI)
		Log.debug("opening chest inventory window");
		Inventory inv = ((Chest) chest.getState()).getInventory();
		player.openInventory(inv);
		return true;
	}
	return false;
}
 
Example #30
Source File: PlayerInteractListener.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
  public void onBlockPlaced(BlockPlaceEvent e) {
GameMap gMap = MatchManager.get().getPlayerMap(e.getPlayer());
if (gMap == null) {
	if (e.getBlockPlaced().getType().equals(Material.CHEST) || e.getBlock().getType().equals(Material.TRAPPED_CHEST)) {
		GameMap map = GameMap.getMap(e.getPlayer().getWorld().getName());
		if (map == null) {
			return;
		}
		if (map.isEditing()) {
			Location loc = e.getBlock().getLocation();
			Player player = e.getPlayer();
			new BukkitRunnable() {
				@Override
				public void run() {
					map.addChest((Chest) loc.getBlock().getState(), map.getChestPlacementType());
					if (map.getChestPlacementType() == ChestPlacementType.NORMAL) {
						player.sendMessage(new Messaging.MessageFormatter().setVariable("mapname", map.getDisplayName()).format("maps.addChest"));
					} else if (map.getChestPlacementType() == ChestPlacementType.CENTER) {
						player.sendMessage(new Messaging.MessageFormatter().setVariable("mapname", map.getDisplayName()).format("maps.addCenterChest"));
					}
				}
			}.runTaskLater(SkyWarsReloaded.get(), 2L);
		}
	}
}
  }