Java Code Examples for org.bukkit.block.BlockState

The following examples show how to use org.bukkit.block.BlockState. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Modern-LWC   Source File: LWCBlockListener.java    License: MIT License 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onBlockMultiPlace(BlockMultiPlaceEvent event) {
    LWC lwc = plugin.getLWC();
    Block block = event.getBlock();

    if (block.getType().name().contains("_BED")) {
        for (BlockState state : event.getReplacedBlockStates()) {
            Protection protection = lwc.findProtection(state);

            if (protection != null) {
                event.setCancelled(true);
                return;
            }
        }
    }
}
 
Example 2
Source Project: BetonQuest   Source File: DoorEvent.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected Void execute(String playerID) throws QuestRuntimeException {
    Block block = loc.getLocation(playerID).getBlock();
    BlockState state = block.getState();
    MaterialData data = state.getData();
    if (data instanceof Openable) {
        Openable openable = (Openable) data;
        switch (type) {
            case ON:
                openable.setOpen(true);
                break;
            case OFF:
                openable.setOpen(false);
                break;
            case TOGGLE:
                openable.setOpen(!openable.isOpen());
                break;
        }
        state.setData((MaterialData) openable);
        state.update();
    }
    return null;
}
 
Example 3
Source Project: Crazy-Crates   Source File: QuadCrateSession.java    License: MIT License 6 votes vote down vote up
private void rotateChest(Block chest, Integer direction) {
    BlockFace blockFace;
    switch (direction) {
        case 0://East
            blockFace = BlockFace.WEST;
            break;
        case 1://South
            blockFace = BlockFace.NORTH;
            break;
        case 2://West
            blockFace = BlockFace.EAST;
            break;
        case 3://North
            blockFace = BlockFace.SOUTH;
            break;
        default:
            blockFace = BlockFace.DOWN;
            break;
    }
    BlockState state = chest.getState();
    state.setData(new Chest(blockFace));
    state.update();
}
 
Example 4
Source Project: PGM   Source File: Renewable.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
boolean renew(BlockVector pos, MaterialData material) {
  // We need to do the entity check here rather than canRenew, because we are not
  // notified when entities move in our out of the way.
  if (!isClearOfEntities(pos)) return false;

  Location location = pos.toLocation(match.getWorld());
  Block block = location.getBlock();
  BlockState newState = location.getBlock().getState();
  newState.setMaterialData(material);

  BlockRenewEvent event = new BlockRenewEvent(block, newState, this);
  match.callEvent(event); // Our own handler will get this and remove the block from the pool
  if (event.isCancelled()) return false;

  newState.update(true, true);

  if (definition.particles || definition.sound) {
    Materials.playBreakEffect(location, material);
  }

  return true;
}
 
Example 5
Source Project: Skript   Source File: ExprColorOf.java    License: GNU General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("deprecated")
@Nullable
private Colorable getColorable(Object colorable) {
	if (colorable instanceof Item || colorable instanceof ItemType) {
		ItemStack item = colorable instanceof Item ?
				((Item) colorable).getItemStack() : ((ItemType) colorable).getRandom();
		
		if (item == null)
			return null;
		MaterialData data = item.getData();
		
		if (data instanceof Colorable)
			return (Colorable) data;
	} else if (colorable instanceof Block) {
		BlockState state = ((Block) colorable).getState();
		
		if (state instanceof Colorable)
			return (Colorable) state;
	} else if (colorable instanceof Colorable) {
		return (Colorable) colorable;
	}
	return null;
}
 
Example 6
Source Project: Modern-LWC   Source File: ProtectionFinder.java    License: MIT License 6 votes vote down vote up
/**
 * From the matched blocks calculate and store the blocks that are protectable
 */
private void calculateProtectables() {
    // reset the matched protectables
    protectables.clear();
    searched = false;

    // if there's only 1 block it was already checked (the base block)
    int size = blocks.size();
    if (size == 1) {
        return;
    }

    // go through the blocks
    for (int index = 1; index < size; index++) {
        BlockState state = blocks.get(index);

        if (lwc.isProtectable(state)) {
            protectables.add(state);
        }
    }
}
 
Example 7
Source Project: BedWars   Source File: LegacyRegion.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void putOriginalBlock(Location loc, BlockState block) {
	if (!block.getType().name().equals("BED_BLOCK")) {
		brokenBlocks.add(loc.getBlock());
	}

    if (block.getData() instanceof Directional) {
        brokenBlockFace.put(loc.getBlock(), ((Directional) block.getData()).getFacing());
    }

    brokenBlockTypes.put(loc.getBlock(), block.getType());
    brokenBlockData.put(loc.getBlock(), block.getData().getData());

    if (block.getData() instanceof Redstone) {
        brokenBlockPower.put(loc.getBlock(), ((Redstone) block.getData()).isPowered());
    }

    if (block instanceof Colorable) {
        // Save bed color on 1.12.x
        brokenBlockColors.put(loc.getBlock(), ((Colorable) block).getColor());
    }
    
    if (isBedHead(block)) {
    	brokenBeds.put(loc.getBlock(), getBedNeighbor(loc.getBlock()));
    }
}
 
Example 8
Source Project: Modern-LWC   Source File: ProtectionFinder.java    License: MIT License 6 votes vote down vote up
/**
 * Load the protection for the calculated protectables.
 * Returns NULL if no protection was found.
 *
 * @param noAutoCache if a match is found, don't cache it to be the protection we use
 * @return
 */
public Protection loadProtection(boolean noAutoCache) {
    // Do we have a result already cached?
    if (searched) {
        return matchedProtection;
    }

    // Calculate the protectables
    calculateProtectables();
    searched = true;

    for (BlockState block : protectables) {
        if (tryLoadProtection(block, noAutoCache) == Result.E_FOUND) {
            return matchedProtection;
        }
    }

    return null;
}
 
Example 9
Source Project: RedProtect   Source File: BlockListener.java    License: GNU General Public License v3.0 6 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onStructureGrow(StructureGrowEvent e) {
    RedProtect.get().logger.debug(LogLevel.BLOCKS, "BlockListener - Is StructureGrowEvent event");
    if (!RedProtect.get().config.configRoot().region_settings.deny_structure_bypass_regions) {
        return;
    }
    Region rfrom = RedProtect.get().rm.getTopRegion(e.getLocation());
    for (BlockState bstt : e.getBlocks()) {
        Region rto = RedProtect.get().rm.getTopRegion(bstt.getLocation());
        Block bloc = bstt.getLocation().getBlock();
        //deny blocks spread in/out regions
        if (rfrom != null && rto != null && rfrom != rto && !rfrom.sameLeaders(rto)) {
            bstt.setType(bloc.getType());
        }
        if (rfrom == null && rto != null) {
            bstt.setType(bloc.getType());
        }
        if (rfrom != null && rto == null) {
            bstt.setType(bloc.getType());
        }
        bstt.update();
    }
}
 
Example 10
@EventWrapper
public void onBlockIgnite(final BlockIgniteEvent event) {
    // Flint & steel generates a BlockPlaceEvent
    if(event.getCause() == BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL) return;

    BlockState oldState = event.getBlock().getState();
    BlockState newState = BlockStateUtils.cloneWithMaterial(event.getBlock(), Material.FIRE);
    ParticipantState igniter = null;

    if(event.getIgnitingEntity() != null) {
        // The player themselves using flint & steel, or any of
        // several types of owned entity starting or spreading a fire.
        igniter = entityResolver.getOwner(event.getIgnitingEntity());
    } else if(event.getIgnitingBlock() != null) {
        // Fire, lava, or flint & steel in a dispenser
        igniter = blockResolver.getOwner(event.getIgnitingBlock());
    }

    callEvent(event, oldState, newState, igniter);
}
 
Example 11
Source Project: XSeries   Source File: XBlock.java    License: 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 12
Source Project: Kettle   Source File: CraftChunk.java    License: GNU General Public License v3.0 6 votes vote down vote up
public BlockState[] getTileEntities() {
    int index = 0;
    net.minecraft.world.chunk.Chunk chunk = getHandle();

    BlockState[] entities = new BlockState[chunk.getTileEntityMap().size()];

    for (Object obj : chunk.getTileEntityMap().keySet().toArray()) {
        if (!(obj instanceof BlockPos)) {
            continue;
        }

        BlockPos position = (BlockPos) obj;
        entities[index++] = worldServer.getWorld().getBlockAt(position.getX(), position.getY(), position.getZ()).getState();
    }

    return entities;
}
 
Example 13
Source Project: ProjectAres   Source File: Renewable.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
boolean renew(BlockVector pos, MaterialData material) {
    // We need to do the entity check here rather than canRenew, because we are not
    // notified when entities move in our out of the way.
    if(!isClearOfEntities(pos)) return false;

    Location location = pos.toLocation(match.getWorld());
    Block block = location.getBlock();
    BlockState newState = location.getBlock().getState();
    newState.setMaterialData(material);

    BlockRenewEvent event = new BlockRenewEvent(block, newState, this);
    match.callEvent(event); // Our own handler will get this and remove the block from the pool
    if(event.isCancelled()) return false;

    newState.update(true, true);

    if(definition.particles) {
        NMSHacks.playBlockBreakEffect(match.getWorld(), pos, material.getItemType());
    }

    if(definition.sound) {
        NMSHacks.playBlockPlaceSound(match.getWorld(), pos, material.getItemType(), 1f);
    }

    return true;
}
 
Example 14
Source Project: askyblock   Source File: EntityLimits.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Prevents trees from growing outside of the protected area.
 *
 * @param e - event
 */
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onTreeGrow(final StructureGrowEvent e) {
    if (DEBUG) {
        plugin.getLogger().info(e.getEventName());
    }
    // Check world
    if (!IslandGuard.inWorld(e.getLocation())) {
        return;
    }
    // Check if this is on an island
    Island island = plugin.getGrid().getIslandAt(e.getLocation());
    if (island == null || island.isSpawn()) {
        return;
    }
    Iterator<BlockState> it = e.getBlocks().iterator();
    while (it.hasNext()) {
        BlockState b = it.next();
        if (b.getType() == Material.LOG || b.getType() == Material.LOG_2
                || b.getType() == Material.LEAVES || b.getType() == Material.LEAVES_2) {
            if (!island.onIsland(b.getLocation())) {
                it.remove();
            }
        }
    }
}
 
Example 15
Source Project: PGM   Source File: Renewable.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
MaterialData sampleShuffledMaterial(BlockVector pos) {
  Random random = match.getRandom();
  int range = SHUFFLE_SAMPLE_RANGE;
  int diameter = range * 2 + 1;
  for (int i = 0; i < SHUFFLE_SAMPLE_ITERATIONS; i++) {
    BlockState block =
        snapshot()
            .getOriginalBlock(
                pos.getBlockX() + random.nextInt(diameter) - range,
                pos.getBlockY() + random.nextInt(diameter) - range,
                pos.getBlockZ() + random.nextInt(diameter) - range);
    if (definition.shuffleableBlocks.query(new BlockQuery(block)).isAllowed())
      return block.getMaterialData();
  }
  return null;
}
 
Example 16
private void replaceBlock(BlockDrops drops, Block block, MatchPlayer player) {
  if (drops.replacement != null) {
    EntityChangeBlockEvent event =
        new EntityChangeBlockEvent(
            player.getBukkit(),
            block,
            drops.replacement.getItemType(),
            drops.replacement.getData());
    match.callEvent(event);

    if (!event.isCancelled()) {
      BlockState state = block.getState();
      state.setType(drops.replacement.getItemType());
      state.setData(drops.replacement);
      state.update(true, true);
    }
  }
}
 
Example 17
Source Project: BedWars   Source File: Game.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean blockPlace(GamePlayer player, Block block, BlockState replaced, ItemStack itemInHand) {
    if (status != GameStatus.RUNNING) {
        return false; // ?
    }
    if (player.isSpectator) {
        return false;
    }
    if (Main.isFarmBlock(block.getType())) {
        return true;
    }
    if (!GameCreator.isInArea(block.getLocation(), pos1, pos2)) {
        return false;
    }

    BedwarsPlayerBuildBlock event = new BedwarsPlayerBuildBlock(this, player.player, getPlayerTeam(player), block,
            itemInHand, replaced);
    Main.getInstance().getServer().getPluginManager().callEvent(event);

    if (event.isCancelled()) {
        return false;
    }

    if (replaced.getType() != Material.AIR) {
        if (region.isBlockAddedDuringGame(replaced.getLocation())) {
            return true;
        } else if (Main.isBreakableBlock(replaced.getType()) || region.isLiquid(replaced.getType())) {
            region.putOriginalBlock(block.getLocation(), replaced);
        } else {
            return false;
        }
    }
    region.addBuiltDuringGame(block.getLocation());

    return true;
}
 
Example 18
Source Project: MineTinker   Source File: GiveCommand.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) {
	List<String> result = new ArrayList<>();
	switch (args.length) {
		case 2:
			for (Player player : Bukkit.getOnlinePlayers()) {
				result.add(player.getName());
			}
			result.add("@a");
			result.add("@r");

			if (sender instanceof Entity || sender instanceof BlockState) {
				result.add("@aw");
				result.add("@p");
				result.add("@rw");
			}
			break;
		case 3:
			for (ToolType type : ToolType.values()) {
				for (Material mat : type.getToolMaterials()) {
					result.add(mat.toString());
				}
			}
			if (ConfigurationManager.getConfig("BuildersWand.yml").getBoolean("enabled")) {
				for (ItemStack wand : BuildersWandListener.getWands()) {
					result.add(wand.getItemMeta().getDisplayName().replaceAll(" ", "_"));
				}
			}
			break;
	}
	return result;
}
 
Example 19
private IEventQuery makeBlockQuery(Event event, Entity entity, BlockState block) {
    if(entity instanceof Player) {
        MatchPlayer player = this.match.getPlayer((Player) entity);
        if(MatchPlayers.canInteract(player)) {
            return new PlayerBlockEventQuery(player, event, block);
        }
    }
    return new BlockEventQuery(event, block);
}
 
Example 20
Source Project: Modern-LWC   Source File: LWC.java    License: MIT License 5 votes vote down vote up
/**
 * Look for a double chest adjacent to a chest
 *
 * @param block
 * @return
 */
public Block findAdjacentDoubleChest(Block block) {
    if (!DoubleChestMatcher.PROTECTABLES_CHESTS.contains(block.getType())) {
        throw new UnsupportedOperationException(
                "findAdjacentDoubleChest() cannot be called on a: " + block.getType());
    }

    BlockState baseBlockState = block.getState();
    Chest baseBlockData = null;
    try {
        baseBlockData = (Chest) baseBlockState.getBlockData();
    } catch (ClassCastException e) {
        return null;
    }

    // get the block face for the neighboring chest if there is one
    BlockFace neighboringBlockFace = DoubleChestMatcher.getNeighboringChestBlockFace(baseBlockData);
    if (neighboringBlockFace == null) {
        return null;
    }

    // if the neighboring block is a chest as well, we have a match
    Block neighboringBlock = baseBlockState.getBlock().getRelative(neighboringBlockFace);
    if (baseBlockState.getType() == neighboringBlock.getType()) {
        return block;
    }

    return null;
}
 
Example 21
Source Project: civcraft   Source File: CivData.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static boolean canGrowMushroom(BlockState blockState) {
	int[][] offset = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
	boolean hasAir = false;
	for (int i = 0; i < 4; i++) {
		Block nextBlock = blockState.getBlock().getRelative(offset[i][0], 0, offset[i][1]);
		if (ItemManager.getId(nextBlock) == CivData.AIR) {
			hasAir = true;
		}
	}
	return hasAir;
}
 
Example 22
Source Project: IridiumSkyblock   Source File: v1_13_R1.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setBlockFast(Block block, int blockId, byte data) {
    BlockState state = block.getState();
    if (state.getType().name().endsWith("AIR") && blockId == 0) return;
    if (state instanceof InventoryHolder) {
        ((InventoryHolder) state).getInventory().clear();
    }
    XMaterial material = XMaterial.requestOldXMaterial(blockId, (byte) 0);
    if (material != null && material.parseMaterial() != null) {
        block.setBlockData(IridiumSkyblock.getInstance().fromLegacy(material.parseMaterial(), data), false);
    }
}
 
Example 23
Source Project: IridiumSkyblock   Source File: XBlock.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void setAge(Block block, int age) {
    if (XMaterial.ISFLAT) {
        if (!(block.getBlockData() instanceof Ageable)) return;
        Ageable ageable = (Ageable) block.getBlockData();
        ageable.setAge(age);
    }

    BlockState state = block.getState();
    MaterialData data = state.getData();
    data.setData((byte) age);
    state.update(true);
}
 
Example 24
Source Project: IridiumSkyblock   Source File: XBlock.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Can be used on cauldron.
 */
public static boolean setFluidLevel(Block block, int level) {
    if (XMaterial.ISFLAT) {
        if (!(block.getBlockData() instanceof Levelled)) return false;
        Levelled levelled = (Levelled) block.getBlockData();
        levelled.setLevel(level);
        return true;
    }

    BlockState state = block.getState();
    MaterialData data = state.getData();
    data.setData((byte) level);
    state.update(true);
    return false;
}
 
Example 25
Source Project: Kettle   Source File: CraftEventFactory.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * BlockFadeEvent
 */
public static BlockFadeEvent callBlockFadeEvent(Block block, net.minecraft.block.Block type) {
    BlockState state = block.getState();
    state.setTypeId(net.minecraft.block.Block.getIdFromBlock(type));

    BlockFadeEvent event = new BlockFadeEvent(block, state);
    Bukkit.getPluginManager().callEvent(event);
    return event;
}
 
Example 26
private void replaceBlock(BlockDrops drops, Block block, MatchPlayer player) {
    if(drops.replacement != null) {
        EntityChangeBlockEvent event = new EntityChangeBlockEvent(player.getBukkit(), block, drops.replacement);
        getMatch().callEvent(event);

        if(!event.isCancelled()) {
            BlockState state = block.getState();
            state.setType(drops.replacement.getItemType());
            state.setData(drops.replacement);
            state.update(true, true);
        }
    }
}
 
Example 27
Source Project: Skript   Source File: InventorySlot.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String toString(@Nullable Event e, boolean debug) {
	InventoryHolder holder = invi.getHolder();
	
	if (holder instanceof BlockState)
		holder = new BlockInventoryHolder((BlockState) holder);
	
	if (invi.getHolder() != null) {
		if (invi instanceof CraftingInventory) // 4x4 crafting grid is contained in player too!
			return "crafting slot " + index + " of " + Classes.toString(holder);
		
		return "inventory slot " + index + " of " + Classes.toString(holder);
	}
	return "inventory slot " + index + " of " + Classes.toString(invi);
}
 
Example 28
Source Project: GriefDefender   Source File: SignUtil.java    License: MIT License 5 votes vote down vote up
public static boolean isSign(Block block) {
    if (block == null) {
        return false;
    }

    final BlockState state = block.getState();
    if (!(state instanceof Sign)) {
        return false;
    }

    return true;
}
 
Example 29
@Override
public boolean matches(IBlockQuery query) {
    final BlockState block = query.getBlock();
    return block.getY() == 0 ||
           (!query.getMatch().needMatchModule(WorldProblemMatchModule.class).wasBlock36(block.getX(), 0, block.getZ()) &&
            block.getWorld().getBlockAt(block.getX(), 0, block.getZ()).getType() == Material.AIR);
}
 
Example 30
Source Project: XSeries   Source File: XBlock.java    License: MIT License 5 votes vote down vote up
public static int getAge(Block block) {
    if (ISFLAT) {
        if (!(block.getBlockData() instanceof Ageable)) return 0;
        Ageable ageable = (Ageable) block.getBlockData();
        return ageable.getAge();
    }

    BlockState state = block.getState();
    MaterialData data = state.getData();
    return data.getData();
}
 
Example 31
Source Project: XSeries   Source File: XBlock.java    License: MIT License 5 votes vote down vote up
public static void setAge(Block block, int age) {
    if (ISFLAT) {
        if (!(block.getBlockData() instanceof Ageable)) return;
        Ageable ageable = (Ageable) block.getBlockData();
        ageable.setAge(age);
    }

    BlockState state = block.getState();
    MaterialData data = state.getData();
    data.setData((byte) age);
    state.update(true);
}
 
Example 32
Source Project: XSeries   Source File: XBlock.java    License: MIT License 5 votes vote down vote up
/**
 * Can be used on cauldron.
 */
public static boolean setFluidLevel(Block block, int level) {
    if (ISFLAT) {
        if (!(block.getBlockData() instanceof Levelled)) return false;
        Levelled levelled = (Levelled) block.getBlockData();
        levelled.setLevel(level);
        return true;
    }

    BlockState state = block.getState();
    MaterialData data = state.getData();
    data.setData((byte) level);
    state.update(true);
    return false;
}
 
Example 33
Source Project: BedwarsRel   Source File: ResourceSpawner.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
  Location dropLocation = this.location.clone();
  for (ItemStack itemStack : this.resources) {
    ItemStack item = itemStack.clone();

    BedwarsResourceSpawnEvent resourceSpawnEvent =
        new BedwarsResourceSpawnEvent(this.game, this.location, item);
    BedwarsRel.getInstance().getServer().getPluginManager().callEvent(resourceSpawnEvent);

    if (resourceSpawnEvent.isCancelled()) {
      return;
    }

    item = resourceSpawnEvent.getResource();

    if (BedwarsRel.getInstance().getBooleanConfig("spawn-resources-in-chest", true)) {
      BlockState blockState = dropLocation.getBlock().getState();
      if (blockState instanceof Chest) {
        Chest chest = (Chest) blockState;
        if (canContainItem(chest.getInventory(), item)) {
          chest.getInventory().addItem(item);
          continue;
        } else {
          dropLocation.setY(dropLocation.getY() + 1);
        }
      }
    }
    dropItem(dropLocation, item);
  }
}
 
Example 34
Source Project: BedwarsRel   Source File: GameJoinSign.java    License: GNU General Public License v3.0 5 votes vote down vote up
public Sign getSign() {
  BlockState state = this.signLocation.getBlock().getState();

  if (!(state instanceof Sign)) {
    return null;
  }

  return (Sign) state;
}
 
Example 35
Source Project: Kettle   Source File: CraftEventFactory.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Block place methods
 */
public static BlockMultiPlaceEvent callBlockMultiPlaceEvent(World world, EntityPlayer who, EnumHand hand, List<BlockState> blockStates, int clickedX, int clickedY, int clickedZ) {
    CraftWorld craftWorld = world.getWorld();
    CraftServer craftServer = world.getServer();
    Player player = (Player) who.getBukkitEntity();

    Block blockClicked = craftWorld.getBlockAt(clickedX, clickedY, clickedZ);

    boolean canBuild = true;
    for (int i = 0; i < blockStates.size(); i++) {
        if (!canBuild(craftWorld, player, blockStates.get(i).getX(), blockStates.get(i).getZ())) {
            canBuild = false;
            break;
        }
    }

    org.bukkit.inventory.ItemStack item;
    if (hand == EnumHand.MAIN_HAND) {
        item = player.getInventory().getItemInMainHand();
    } else {
        item = player.getInventory().getItemInOffHand();
    }

    BlockMultiPlaceEvent event = new BlockMultiPlaceEvent(blockStates, blockClicked, item, player, canBuild);
    craftServer.getPluginManager().callEvent(event);

    return event;
}
 
Example 36
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void dispenserNukes(BlockTransformEvent event) {
    BlockState oldState = event.getOldState();
    if(oldState instanceof Dispenser &&
       this.properties.dispenserNukeLimit > 0 &&
       this.properties.dispenserNukeMultiplier > 0 &&
       event.getCause() instanceof EntityExplodeEvent) {

        EntityExplodeEvent explodeEvent = (EntityExplodeEvent) event.getCause();
        Dispenser dispenser = (Dispenser) oldState;
        int tntLimit = Math.round(this.properties.dispenserNukeLimit / this.properties.dispenserNukeMultiplier);
        int tntCount = 0;

        for(ItemStack stack : dispenser.getInventory().contents()) {
            if(stack != null && stack.getType() == Material.TNT) {
                int transfer = Math.min(stack.getAmount(), tntLimit - tntCount);
                if(transfer > 0) {
                    stack.setAmount(stack.getAmount() - transfer);
                    tntCount += transfer;
                }
            }
        }

        tntCount = (int) Math.ceil(tntCount * this.properties.dispenserNukeMultiplier);

        for(int i = 0; i < tntCount; i++) {
            TNTPrimed tnt = this.getMatch().getWorld().spawn(BlockUtils.base(dispenser), TNTPrimed.class);

            tnt.setFuseTicks(10 + this.getMatch().getRandom().nextInt(10)); // between 0.5 and 1.0 seconds, same as vanilla TNT chaining

            Random random = this.getMatch().getRandom();
            Vector velocity = new Vector(random.nextGaussian(), random.nextGaussian(), random.nextGaussian()); // uniform random direction
            velocity.normalize().multiply(0.5 + 0.5 * random.nextDouble());
            tnt.setVelocity(velocity);

            callPrimeEvent(tnt, explodeEvent.getEntity(), false);
        }
    }
}
 
Example 37
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onSignChange(SignChangeEvent event) {
    Player player = event.getPlayer();
    Block block = event.getBlock();
    BlockState state = block.getState();
    if (!(state instanceof Sign)) {
        return;
    }

    String[] lines = event.getLines();

    // Group Signs
    if (plugin.getEditWorld(player.getWorld()) == null) {
        if (!DPermission.hasPermission(player, DPermission.SIGN)) {
            return;
        }

        if (!lines[0].equalsIgnoreCase(GlobalProtection.SIGN_TAG)) {
            return;
        }

        if (lines[1].equalsIgnoreCase(GroupSign.GROUP_SIGN_TAG)) {
            if (GroupSign.tryToCreate(plugin, event) != null) {
                event.setCancelled(true);
            }

        } else if (lines[1].equalsIgnoreCase(GameSign.GAME_SIGN_TAG)) {
            if (GameSign.tryToCreate(plugin, event) != null) {
                event.setCancelled(true);
            }

        } else if (lines[1].equalsIgnoreCase(LeaveSign.LEAVE_SIGN_TAG)) {
            Sign sign = (Sign) state;
            new LeaveSign(plugin, plugin.getGlobalProtectionCache().generateId(LeaveSign.class, sign.getWorld()), sign);
            event.setCancelled(true);
        }
    }
}
 
Example 38
Source Project: Skript   Source File: MagicBlockCompat.java    License: GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("null")
public MagicBlockValues(BlockState block) {
	this.id = ItemUtils.asItem(block.getType());
	this.data = block.getRawData(); // Some black magic here, please look away...
	// We don't know whether block data 0 has been set explicitly
	this.itemFlags = ItemFlags.CHANGED_DURABILITY;
}
 
Example 39
Source Project: WorldGuardExtraFlagsPlugin   Source File: EntityListener.java    License: MIT License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true)
public void onPortalCreateEvent(PortalCreateEvent event)
{
	for(BlockState block : event.getBlocks())
	{
		ApplicableRegionSet regions = this.plugin.getWorldGuardCommunicator().getRegionContainer().createQuery().getApplicableRegions(block.getLocation());
		if (regions.queryValue(null, Flags.NETHER_PORTALS) == State.DENY)
		{
			event.setCancelled(true);
			break;
		}
	}
}
 
Example 40
/**
 * Get the {@link BlockState} after the {@link Block} was transformed.
 *
 * @return The current {@link BlockState}.
 */
public final BlockState getNewState() {
  if (drops == null || drops.replacement == null) {
    return newState;
  } else {
    final BlockState state = newState.getBlock().getState();
    state.setType(drops.replacement.getItemType());
    state.setData(drops.replacement);
    return state;
  }
}