Java Code Examples for org.bukkit.block.Block#setType()

The following examples show how to use org.bukkit.block.Block#setType() . 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: RainbowTickHandler.java    From Slimefun4 with GNU General Public License v3.0 7 votes vote down vote up
@Override
public void tick(Block b, SlimefunItem item, Config data) {
    if (b.getType() == Material.AIR) {
        // The block was broken, setting the Material now would result in a
        // duplication glitch
        return;
    }

    if (waterlogged) {
        BlockData blockData = b.getBlockData();
        b.setType(material, true);

        if (blockData instanceof Waterlogged && ((Waterlogged) blockData).isWaterlogged()) {
            Waterlogged block = (Waterlogged) b.getBlockData();
            block.setWaterlogged(true);
            b.setBlockData(block);
        }
    }
    else {
        b.setType(material, false);
    }
}
 
Example 2
Source File: ExplosiveShovel.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void breakBlock(Player p, ItemStack item, Block b, int fortune, List<ItemStack> drops) {
    if (MaterialTools.getBreakableByShovel().contains(b.getType()) && SlimefunPlugin.getProtectionManager().hasPermission(p, b.getLocation(), ProtectableAction.BREAK_BLOCK)) {
        SlimefunPlugin.getProtectionManager().logAction(p, b, ProtectableAction.BREAK_BLOCK);

        b.getWorld().playEffect(b.getLocation(), Effect.STEP_SOUND, b.getType());

        for (ItemStack drop : b.getDrops(getItem())) {
            if (drop != null) {
                b.getWorld().dropItemNaturally(b.getLocation(), drop);
            }
        }

        b.setType(Material.AIR);
        damageItem(p, item);
    }
}
 
Example 3
Source File: DoubleGoldListener.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
@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);
    }
}
 
Example 4
Source File: XBlock.java    From XSeries with MIT License 6 votes vote down vote up
/**
 * Sets the type of any block that can be colored.
 *
 * @param block the block to color.
 * @param color the color to use.
 * @return true if the block can be colored, otherwise false.
 */
public static boolean setColor(Block block, DyeColor color) {
    if (ISFLAT) {
        String type = block.getType().name();
        int index = type.indexOf('_');
        if (index == -1) return false;

        String realType = type.substring(index);
        Material material = Material.getMaterial(color.name() + '_' + realType);
        if (material == null) return false;
        block.setType(material);
        return true;
    }

    BlockState state = block.getState();
    state.setRawData(color.getWoolData());
    state.update(true);
    return false;
}
 
Example 5
Source File: TilesCustomNBTInjectorTest.java    From Item-NBT-API with MIT License 6 votes vote down vote up
@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);
		}
	}
}
 
Example 6
Source File: Game.java    From BedwarsRel with GNU General Public License v3.0 6 votes vote down vote up
private void dropTargetBlock(Block targetBlock) {
  if (targetBlock.getType().equals(Material.BED_BLOCK)) {
    Block bedHead;
    Block bedFeet;
    Bed bedBlock = (Bed) targetBlock.getState().getData();

    if (!bedBlock.isHeadOfBed()) {
      bedFeet = targetBlock;
      bedHead = Utils.getBedNeighbor(bedFeet);
    } else {
      bedHead = targetBlock;
      bedFeet = Utils.getBedNeighbor(bedHead);
    }

    if (!BedwarsRel.getInstance().getCurrentVersion().startsWith("v1_12")) {
      bedFeet.setType(Material.AIR);
    } else {
      bedHead.setType(Material.AIR);
    }
  } else {
    targetBlock.setType(Material.AIR);
  }
}
 
Example 7
Source File: BlockPlacer.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
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);
    }
}
 
Example 8
Source File: ExoticGarden.java    From ExoticGarden with GNU General Public License v3.0 5 votes vote down vote up
public static ItemStack harvestPlant(Block block) {
	SlimefunItem item = BlockStorage.check(block);
	if (item == null) return null;

	for (Berry berry : getBerries()) {
		if (item.getID().equalsIgnoreCase(berry.getID())) {
			switch (berry.getType()) {
				case ORE_PLANT:
				case DOUBLE_PLANT:
					Block plant = block;

					if (Tag.LEAVES.isTagged(block.getType()))
						block = block.getRelative(BlockFace.UP);
					else
						plant = block.getRelative(BlockFace.DOWN);

					BlockStorage._integrated_removeBlockInfo(block.getLocation(), false);
					block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, Material.OAK_LEAVES);
					block.setType(Material.AIR);

					plant.setType(Material.OAK_SAPLING);
					BlockStorage._integrated_removeBlockInfo(plant.getLocation(), false);
					BlockStorage.store(plant, getItem(berry.toBush()));
					return berry.getItem();
				default:
					block.setType(Material.OAK_SAPLING);
					BlockStorage._integrated_removeBlockInfo(block.getLocation(), false);
					BlockStorage.store(block, getItem(berry.toBush()));
					return berry.getItem();
			}
		}
	}

	return null;
}
 
Example 9
Source File: ProjectileMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onProjectileHitEvent(ProjectileHitEvent event) {
    final Projectile projectile = event.getEntity();
    final ProjectileDefinition projectileDefinition = Projectiles.getProjectileDefinition(projectile);
    if(projectileDefinition == null) return;

    final Filter filter = projectileDefinition.destroyFilter();
    if(filter == null) return;

    final BlockIterator blockIterator = new BlockIterator(projectile.getWorld(), projectile.getLocation().toVector(), projectile.getVelocity().normalize(), 0d, 2);
    Block hitBlock = null;
    while(blockIterator.hasNext()) {
        hitBlock = blockIterator.next();
        if(hitBlock.getType() != Material.AIR) break;
    }

    if(hitBlock != null) {
        final MatchPlayer shooter = projectile.getShooter() instanceof Player ? getMatch().getPlayer((Player) projectile.getShooter()) : null;
        final IQuery query = shooter != null ? new PlayerBlockEventQuery(shooter, event, hitBlock.getState())
                                             : new BlockEventQuery(event, hitBlock);

        if(filter.query(query).isAllowed()) {
            final BlockTransformEvent bte = new BlockTransformEvent(event, hitBlock, Material.AIR);
            match.callEvent(bte);

            if(!bte.isCancelled()) {
                hitBlock.setType(Material.AIR);
                projectile.remove();
            }
        }
    }
}
 
Example 10
Source File: DoubleOresListener.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onBlockBreak(BlockBreakEvent e) {

    if (isActivated(Scenario.VEINMINER)) {
        return;
    }

    Block block = e.getBlock();
    Location loc = e.getBlock().getLocation().add(0.5, 0, 0.5);

    switch (block.getType()) {
        case IRON_ORE:
            block.setType(Material.AIR);
            loc.getWorld().dropItem(loc, new ItemStack(Material.IRON_INGOT,2));
            UhcItems.spawnExtraXp(loc,2);
            break;
        case GOLD_ORE:
            block.setType(Material.AIR);
            loc.getWorld().dropItem(loc, new ItemStack(Material.GOLD_INGOT,2));
            if (isActivated(Scenario.DOUBLEGOLD)){
                loc.getWorld().dropItem(loc, new ItemStack(Material.GOLD_INGOT,2));
            }
            UhcItems.spawnExtraXp(loc,3);
            break;
        case DIAMOND_ORE:
            block.setType(Material.AIR);
            loc.getWorld().dropItem(loc, new ItemStack(Material.DIAMOND,2));
            UhcItems.spawnExtraXp(loc,4);
            break;
        case SAND:
            block.setType(Material.AIR);
            loc.getWorld().dropItem(loc, new ItemStack(Material.GLASS));
            break;
        case GRAVEL:
            block.setType(Material.AIR);
            loc.getWorld().dropItem(loc,new ItemStack(Material.FLINT));
            break;
    }

}
 
Example 11
Source File: EasyHarvestListener.java    From MineTinker with GNU General Public License v3.0 5 votes vote down vote up
private static void replantCrops(Player player, Block block, Material material) {
	if (MineTinker.getPlugin().getConfig().getBoolean("EasyHarvest.replant")) {
		if (!player.hasPermission("minetinker.easyharvest.replant")) {
			return;
		}

		for (ItemStack itemStack : player.getInventory().getContents()) {
			if (itemStack == null) {
				// This is necessary as even though this is annotated @NotNull, it's still null sometimes
				continue;
			}

			if (material == Material.BEETROOTS && itemStack.getType() == Material.BEETROOT_SEEDS) {
				itemStack.setAmount(itemStack.getAmount() - 1);
				block.setType(material);
				break;
			} else if (material == Material.CARROTS && itemStack.getType() == Material.CARROT) {
				itemStack.setAmount(itemStack.getAmount() - 1);
				block.setType(material);
				break;
			} else if (material == Material.POTATOES && itemStack.getType() == Material.POTATO) {
				itemStack.setAmount(itemStack.getAmount() - 1);
				block.setType(material);
				break;
			} else if (material == Material.WHEAT && itemStack.getType() == Material.WHEAT_SEEDS) {
				itemStack.setAmount(itemStack.getAmount() - 1);
				block.setType(material);
				break;
			} else if (material == Material.NETHER_WART && itemStack.getType() == Material.NETHER_WART) {
				itemStack.setAmount(itemStack.getAmount() - 1);
				block.setType(material);
				break;
			}
		}
	}
}
 
Example 12
Source File: XBlock.java    From XSeries with MIT License 5 votes vote down vote up
/**
 * Can be furnaces or redstone lamps.
 */
public static void setLit(Block block, boolean lit) {
    if (ISFLAT) {
        if (!(block.getBlockData() instanceof Lightable)) return;
        Lightable lightable = (Lightable) block.getBlockData();
        lightable.setLit(lit);
        return;
    }

    String name = block.getType().name();
    if (name.endsWith("FURNACE")) block.setType(Material.getMaterial("BURNING_FURNACE"));
    else if (name.startsWith("REDSTONE_LAMP")) block.setType(Material.getMaterial("REDSTONE_LAMP_ON"));
    else block.setType(Material.getMaterial("REDSTONE_TORCH_ON"));
}
 
Example 13
Source File: DisableShulkerboxes.java    From Minepacks with GNU General Public License v3.0 5 votes vote down vote up
private boolean handleShulkerBlock(Block block)
{
	if(SHULKER_BOX_MATERIALS.contains(block.getType()))
	{
		if(removeExisting)
		{
			ShulkerBox shulkerBox = (ShulkerBox) block.getState();
			if(dropExistingContent) Utils.dropInventory(shulkerBox.getInventory(), shulkerBox.getLocation());
			shulkerBox.getInventory().clear();
			block.setType(Material.AIR);
		}
		return true;
	}
	return false;
}
 
Example 14
Source File: JoinSign.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
protected static void onCreation(DungeonsXL plugin, Block startSign, String identifier, int maxElements, int startIfElementsAtLeast) {
    World world = startSign.getWorld();
    BlockFace facing = DungeonsXL.BLOCK_ADAPTER.getFacing(startSign);
    int x = startSign.getX(), y = startSign.getY(), z = startSign.getZ();

    int verticalSigns = (int) Math.ceil((float) (1 + maxElements) / 4);
    while (verticalSigns > 1) {
        Block block = world.getBlockAt(x, y - verticalSigns + 1, z);
        block.setType(startSign.getType(), false);
        DungeonsXL.BLOCK_ADAPTER.setFacing(block, facing);
        verticalSigns--;
    }

    LWCUtil.removeProtection(startSign);
}
 
Example 15
Source File: FlagAnvilSpleef.java    From HeavySpleef with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
@EventHandler
public void onEntityChangeBlockEvent(EntityChangeBlockEvent e) {
	EntityType type = e.getEntityType();
	if (type != EntityType.FALLING_BLOCK) {
		return;
	}
	
	Entity entity = e.getEntity();
	if (!fallingAnvils.contains(entity)) {
		return;
	}
	
	Block block = e.getBlock();
	Block under = block.getRelative(BlockFace.DOWN);
	
	fallingAnvils.remove(entity);
	e.setCancelled(true);		
	
	if (!game.canSpleef(under)) {
		entity.remove();
		return;
	}
	
	Material material = under.getType();
	under.setType(Material.AIR);
	World world = under.getWorld();

       Sound anvilLandSound = Game.getSoundEnumType("ANVIL_LAND");
       if (anvilLandSound != null) {
           world.playSound(block.getLocation(), anvilLandSound, 1.0f, 1.0f);
       }
	
	if (game.getPropertyValue(GameProperty.PLAY_BLOCK_BREAK)) {
		world.playEffect(under.getLocation(), Effect.STEP_SOUND, material.getId());
	}
}
 
Example 16
Source File: BlockListener.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent e) {
    RedProtect.get().logger.debug(LogLevel.BLOCKS, "BlockListener - Is BlockPlaceEvent event!");

    Player p = e.getPlayer();
    Block b = e.getBlockPlaced();
    World w = p.getWorld();
    Material m = e.getItemInHand().getType();

    boolean antih = RedProtect.get().config.configRoot().region_settings.anti_hopper;
    Region r = RedProtect.get().rm.getTopRegion(b.getLocation());

    if (!RedProtect.get().ph.hasPerm(p, "redprotect.bypass") && antih &&
            (m.equals(Material.HOPPER) || m.name().contains("RAIL"))) {
        int x = b.getX();
        int y = b.getY();
        int z = b.getZ();
        Block ib = w.getBlockAt(x, y + 1, z);
        if (!cont.canBreak(p, ib) || !cont.canBreak(p, b)) {
            RedProtect.get().lang.sendMessage(p, "blocklistener.container.chestinside");
            e.setCancelled(true);
            return;
        }
    }

    if (r == null && canPlaceList(p.getWorld(), b.getType().name())) {
        return;
    }

    if (r != null) {

        if (!r.canMinecart(p) && (m.name().contains("MINECART") || m.name().contains("BOAT"))) {
            RedProtect.get().lang.sendMessage(p, "blocklistener.region.cantplace");
            e.setCancelled(true);
            return;
        }

        if ((b.getType().name().equals("MOB_SPAWNER") || b.getType().name().equals("SPAWNER")) && r.canPlaceSpawner(p)) {
            return;
        }

        if ((m.name().contains("_HOE") || r.canCrops(b)) && r.canCrops()) {
            return;
        }

        Material type = b.getType();
        if (!r.blockTransform() && type.isBlock() && (
                type.name().contains("SNOW") ||
                        type.name().contains("ICE") ||
                        type.name().contains("CORAL") ||
                        type.name().contains("POWDER"))) {
            b.setType(m);
        }

        if (!r.canBuild(p) && !r.canPlace(b.getType())) {
            RedProtect.get().lang.sendMessage(p, "blocklistener.region.cantbuild");
            e.setCancelled(true);
        }
    }
}
 
Example 17
Source File: DataHandler.java    From MineTinker with GNU General Public License v3.0 4 votes vote down vote up
public static boolean playerBreakBlock(@NotNull Player player, Block block, @NotNull ItemStack itemStack) {
    //Trigger BlockBreakEvent
    BlockBreakEvent breakEvent = new BlockBreakEvent(block, player);
    ItemMeta meta = itemStack.getItemMeta();
    if (meta != null && !meta.hasEnchant(Enchantment.SILK_TOUCH)) breakEvent.setExpToDrop(calculateExp(block.getType()));
    Bukkit.getPluginManager().callEvent(breakEvent);

    //Check if Event got cancelled and if not destroy the block and check if the player can successfully break the blocks (incl. drops)
    //Block#breakNaturally(ItemStack itemStack) can not be used as it drops Items itself (without Event and we don't want that)
    if (!breakEvent.isCancelled()) {
        //Get all drops to drop
        Collection<ItemStack> items = block.getDrops(itemStack);

        //Set Block to Material.AIR (effectively breaks the Block)
        block.setType(Material.AIR);
        //TODO: Play Sound?

        //Check if items need to be dropped
        if (breakEvent.isDropItems()) {
            List<Item> itemEntities = items.stream()
                    .map(entry -> player.getWorld().dropItemNaturally(block.getLocation(), entry)) //World#spawnEntity() does not work for Items
                    .collect(Collectors.toList());

            //Trigger BlockDropItemEvent (internally also used for Directing)
            BlockDropItemEvent event = new BlockDropItemEvent(block, block.getState(), player, new ArrayList<>(itemEntities));
            Bukkit.getPluginManager().callEvent(event);

            //check if Event got cancelled
            if (!event.isCancelled()) {
                //Remove all drops that should be dropped
                itemEntities.removeIf(element -> event.getItems().contains(element));
            }
            itemEntities.forEach(Item::remove);
        }

        //Check if Exp needs to be dropped
        if (breakEvent.getExpToDrop() > 0) {
            //Spawn Experience Orb
            ExperienceOrb orb = (ExperienceOrb) player.getWorld().spawnEntity(block.getLocation(), EntityType.EXPERIENCE_ORB);
            orb.setExperience(breakEvent.getExpToDrop());
        }

        return true;
    }

    return false;
}
 
Example 18
Source File: FlagSplegg.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler
public void onProjectileHit(ProjectileHitEvent event) {
	Projectile projectile = event.getEntity();
	if (!(projectile instanceof Egg)) {
		return;
	}
	
	ProjectileSource source = projectile.getShooter();
	
	if (!(source instanceof Player)) {
		return;
	}
	
	SpleefPlayer shooter = getHeavySpleef().getSpleefPlayer(source);
	Game game = getHeavySpleef().getGameManager().getGame(shooter);
	if (game != this.game) {
		return;
	}
	
	projectile.remove();
	
	if (game == null || game.getGameState() != GameState.INGAME) {
		return;
	}
	
	// Use a BlockIterator to determine where the arrow has hit the ground
	BlockIterator blockIter = new BlockIterator(projectile.getWorld(), 
			projectile.getLocation().toVector(), 
			projectile.getVelocity().normalize(), 
			0, 4);
	
	Block blockHit = null;
	
	while (blockIter.hasNext()) {
		blockHit = blockIter.next();
		
		if (blockHit.getType() != Material.AIR) {
			break;
		}
	}
	
	if (!game.canSpleef(blockHit)) {
		//Cannot remove this block
		return;
	}
	
	game.addBlockBroken(shooter, blockHit);
	Material type = blockHit.getType();
	blockHit.setType(Material.AIR);
	
	World world = blockHit.getWorld();
	
	if (type == Material.TNT) {
		Location spawnLocation = blockHit.getLocation().add(0.5, 0, 0.5);
		TNTPrimed tnt = (TNTPrimed) world.spawnEntity(spawnLocation, EntityType.PRIMED_TNT);
		tnt.setMetadata(TNT_METADATA_KEY, new FixedMetadataValue(getHeavySpleef().getPlugin(), game));
		tnt.setYield(3);
		tnt.setFuseTicks(0);
	} else {
           Sound chickenEggPopSound = Game.getSoundEnumType("CHICKEN_EGG_POP", "CHICKEN_EGG");
           if (chickenEggPopSound != null) {
               projectile.getWorld().playSound(blockHit.getLocation(), chickenEggPopSound, 1.0f, 0.7f);
           }
	}
}
 
Example 19
Source File: FutureBlockReplace.java    From AnnihilationPro with MIT License 4 votes vote down vote up
public FutureBlockReplace(Block b, boolean cobble)
{
	this.state = b.getState();
	b.setType(cobble? Material.COBBLESTONE:Material.AIR);
}
 
Example 20
Source File: TeamBed.java    From DungeonsXL with GNU General Public License v3.0 3 votes vote down vote up
@Override
public boolean onBreak(BlockBreakEvent event) {
    Player breaker = event.getPlayer();
    if (owner.getMembers().contains(breaker)) {
        MessageUtil.sendMessage(breaker, DMessage.ERROR_BLOCK_OWN_TEAM.getMessage());
        return true;
    }

    for (DGamePlayer player : owner.getDGamePlayers()) {
        player.setLives(1);
    }
    owner.setLives(0);

    owner.getGameWorld().sendMessage(DMessage.GROUP_BED_DESTROYED.getMessage(owner.getName(), api.getPlayerCache().getGamePlayer(breaker).getName()));
    Block block1 = event.getBlock();
    if (DungeonsXL.BLOCK_ADAPTER.isBedHead(block)) {
        Block block2 = getAttachedBlock(block1);
        if (block2 != null) {
            block2.setType(VanillaItem.AIR.getMaterial());
        }
    }
    block1.setType(VanillaItem.AIR.getMaterial());
    return true;
}