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

The following examples show how to use org.bukkit.block.Block#getRelative() . 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: TreeGrowthAccelerator.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
protected void tick(Block b) {
    BlockMenu inv = BlockStorage.getInventory(b);

    if (ChargableBlock.getCharge(b) >= ENERGY_CONSUMPTION) {
        for (int x = -RADIUS; x <= RADIUS; x++) {
            for (int z = -RADIUS; z <= RADIUS; z++) {
                Block block = b.getRelative(x, 0, z);

                if (Tag.SAPLINGS.isTagged(block.getType())) {
                    Sapling sapling = (Sapling) block.getBlockData();

                    if (sapling.getStage() < sapling.getMaximumStage() && grow(b, block, inv, sapling)) {
                        return;
                    }
                }
            }
        }
    }
}
 
Example 2
Source File: PlantsListener.java    From ExoticGarden with GNU General Public License v3.0 6 votes vote down vote up
private void dropFruitFromTree(Block block) {
    for (int x = -1; x < 2; x++) {
        for (int y = -1; y < 2; y++) {
            for (int z = -1; z < 2; z++) {
                // inspect a cube at the reference
                Block fruit = block.getRelative(x, y, z);
                if (fruit.isEmpty()) continue;

                Location loc = fruit.getLocation();
                SlimefunItem check = BlockStorage.check(loc);
                if (check == null) continue;

                for (Tree tree : ExoticGarden.getTrees()) {
                    if (check.getID().equalsIgnoreCase(tree.getFruitID())) {
                        BlockStorage.clearBlockInfo(loc);
                        ItemStack fruits = check.getItem();
                        fruit.getWorld().playEffect(loc, Effect.STEP_SOUND, Material.OAK_LEAVES);
                        fruit.getWorld().dropItemNaturally(loc, fruits);
                        fruit.setType(Material.AIR);
                        break;
                    }
                }
            }
        }
    }
}
 
Example 3
Source File: BukkitHandler1_13.java    From AreaShop with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Block getSignAttachedTo(Block block) {
	if (block == null) {
		return null;
	}

	BlockState blockState = block.getState();
	if (blockState == null) {
		return null;
	}

	org.bukkit.block.data.BlockData blockData = blockState.getBlockData();
	if (blockData == null) {
		return null;
	}

	if(blockData instanceof WallSign) {
		return block.getRelative(((WallSign) blockData).getFacing().getOppositeFace());
	} else if(blockData instanceof Sign) {
		return block.getRelative(BlockFace.DOWN);
	}

	return null;
}
 
Example 4
Source File: LWC.java    From Modern-LWC with MIT License 6 votes vote down vote up
/**
 * Find a protection that is adjacent to another block on any of the block's 6
 * sides
 *
 * @param block
 * @param ignore
 * @return
 */
public List<Protection> findAdjacentProtectionsOnAllSides(Block block, Block... ignore) {
    BlockFace[] faces = new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST,
            BlockFace.UP, BlockFace.DOWN};
    List<Block> ignoreList = Arrays.asList(ignore);
    List<Protection> found = new ArrayList<Protection>();

    for (BlockFace face : faces) {
        Protection protection;
        Block adjacentBlock = block.getRelative(face);

        if (!ignoreList.contains(adjacentBlock.getLocation())
                && (protection = findProtection(adjacentBlock.getLocation())) != null) {
            found.add(protection);
        }
    }

    return found;
}
 
Example 5
Source File: FluidPump.java    From Slimefun4 with GNU General Public License v3.0 6 votes vote down vote up
protected void tick(Block b) {
    Block fluid = b.getRelative(BlockFace.DOWN);
    Optional<ItemStack> bucket = getFilledBucket(fluid);

    if (bucket.isPresent() && ChargableBlock.getCharge(b) >= ENERGY_CONSUMPTION) {
        BlockMenu menu = BlockStorage.getInventory(b);

        for (int slot : getInputSlots()) {
            if (SlimefunUtils.isItemSimilar(menu.getItemInSlot(slot), new ItemStack(Material.BUCKET), true)) {
                if (!menu.fits(bucket.get(), getOutputSlots())) {
                    return;
                }

                ChargableBlock.addCharge(b, -ENERGY_CONSUMPTION);
                menu.consumeItem(slot);
                menu.pushItem(bucket.get().clone(), getOutputSlots());
                consumeFluid(fluid);

                return;
            }
        }
    }
}
 
Example 6
Source File: FallingBlocksModule.java    From CardinalPGM with MIT License 6 votes vote down vote up
private boolean isBlockAttached(List<Block> scan, Rule rule, List<Vector> alreadyScanned) {
    if (scan.size() == 0) return false;
    List<Block> nextScan = Lists.newArrayList();
    for (Block scanning : scan) {
        if (alreadyScanned.size() > 4096) {
            Bukkit.getConsoleSender().sendMessage("Maximim scan area (4096 blocks) was reached.");
            return true;
        }
        for (BlockFace face : FACES) {
            Block block = scanning.getRelative(face);
            if (alreadyScanned.contains(block.getLocation().toVector())) continue;
            if (rule.getSticky().evaluate(block).equals(FilterState.ALLOW) || (face.equals(BlockFace.DOWN) && !block.getType().equals(Material.AIR))) {
                if (rule.getFilter().evaluate(block).equals(FilterState.ALLOW)) {
                    nextScan.add(block);
                    alreadyScanned.add(block.getLocation().toVector());
                } else return true;
            }
        }
    }
    return isBlockAttached(nextScan, rule, alreadyScanned);
}
 
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: GameSign.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
public void onPlayerInteract(Block block, Player player) {
    DGroup dGroup = (DGroup) plugin.getPlayerGroup(player);
    if (dGroup == null) {
        MessageUtil.sendMessage(player, DMessage.ERROR_JOIN_GROUP.getMessage());
        return;
    }
    if (!dGroup.getLeader().equals(player)) {
        MessageUtil.sendMessage(player, DMessage.ERROR_NOT_LEADER.getMessage());
        return;
    }

    if (dGroup.getGame() != null) {
        MessageUtil.sendMessage(player, DMessage.ERROR_LEAVE_GAME.getMessage());
        return;
    }

    Block topBlock = block.getRelative(0, startSign.getY() - block.getY(), 0);
    if (!(topBlock.getState() instanceof Sign)) {
        return;
    }

    Sign topSign = (Sign) topBlock.getState();

    if (topSign.getLine(0).equals(DMessage.SIGN_GLOBAL_NEW_GAME.getMessage())) {
        if (dungeon == null) {
            MessageUtil.sendMessage(player, DMessage.ERROR_SIGN_WRONG_FORMAT.getMessage());
            return;
        }

        dGroup.setDungeon(dungeon);
        game = new DGame(plugin, dGroup);
        update();

    } else if (topSign.getLine(0).equals(DMessage.SIGN_GLOBAL_JOIN_GAME.getMessage())) {
        game.addGroup(dGroup);
        update();
    }
}
 
Example 9
Source File: AbstractSmeltery.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onInteract(Player p, Block b) {
    Block dispBlock = b.getRelative(BlockFace.DOWN);
    Dispenser disp = (Dispenser) dispBlock.getState();
    Inventory inv = disp.getInventory();
    List<ItemStack[]> inputs = RecipeType.getRecipeInputList(this);

    for (int i = 0; i < inputs.size(); i++) {
        if (canCraft(inv, inputs, i)) {
            ItemStack output = RecipeType.getRecipeOutputList(this, inputs.get(i)).clone();

            if (Slimefun.hasUnlocked(p, output, true)) {
                Inventory outputInv = findOutputInventory(output, dispBlock, inv);

                if (outputInv != null) {
                    craft(p, b, inv, inputs.get(i), output, outputInv);
                }
                else {
                    SlimefunPlugin.getLocalization().sendMessage(p, "machines.full-inventory", true);
                }
            }

            return;
        }
    }

    SlimefunPlugin.getLocalization().sendMessage(p, "machines.unknown-material", true);
}
 
Example 10
Source File: RegionPointProvider.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Indicates whether or not this spawn is safe.
 *
 * @param location Location to check for.
 * @return True or false depending on whether this is a safe spawn point.
 */
private boolean isSafe(Location location) {
  if (!WorldBorders.isInsideBorder(location)) return false;

  Block block = location.getBlock();
  Block above = block.getRelative(BlockFace.UP);
  Block below = block.getRelative(BlockFace.DOWN);

  return block.isEmpty() && above.isEmpty() && BlockVectors.isSupportive(below.getType());
}
 
Example 11
Source File: FlatteningBedUtils.java    From BedWars with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Block getBedNeighbor(Block head) {
    if (!(head.getBlockData() instanceof Bed)) {
        return null;
    }

    if (isBedBlock(head.getRelative(BlockFace.EAST))) {
        return head.getRelative(BlockFace.EAST);
    } else if (isBedBlock(head.getRelative(BlockFace.WEST))) {
        return head.getRelative(BlockFace.WEST);
    } else if (isBedBlock(head.getRelative(BlockFace.SOUTH))) {
        return head.getRelative(BlockFace.SOUTH);
    } else {
        return head.getRelative(BlockFace.NORTH);
    }
}
 
Example 12
Source File: TestCargoNodeListener.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@ParameterizedTest
@SlimefunItemsSource(items = { "CARGO_INPUT_NODE", "CARGO_OUTPUT_NODE", "CARGO_OUTPUT_NODE_2" })
public void testInvalidPlacement(ItemStack item) {
    Player player = server.addPlayer();
    Location l = new Location(player.getWorld(), 190, 50, 400);
    Block b = l.getBlock();
    Block against = b.getRelative(BlockFace.DOWN);

    BlockPlaceEvent event = new BlockPlaceEvent(b, new BlockStateMock(), against, item, player, true, EquipmentSlot.HAND);
    listener.onCargoNodePlace(event);
    Assertions.assertTrue(event.isCancelled());
}
 
Example 13
Source File: MagicWorkbench.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
private Block locateDispenser(Block b) {
    Block block = null;

    if (b.getRelative(1, 0, 0).getType() == Material.DISPENSER) block = b.getRelative(1, 0, 0);
    else if (b.getRelative(0, 0, 1).getType() == Material.DISPENSER) block = b.getRelative(0, 0, 1);
    else if (b.getRelative(-1, 0, 0).getType() == Material.DISPENSER) block = b.getRelative(-1, 0, 0);
    else if (b.getRelative(0, 0, -1).getType() == Material.DISPENSER) block = b.getRelative(0, 0, -1);

    return block;
}
 
Example 14
Source File: VeinGenerator.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Look in a 5 blocks radius to find a non AIR or WATER block
 * @param randBlock
 * @return a non AIR/WATER Block if found, else null
 */
private Block tryAdjustingToProperBlock(Block randBlock) {
	if(randBlock.getType().equals(Material.STONE)){
		return randBlock;
	}
	
	// Descend to go beneath the water in the sea
	if(randBlock.getType().equals(UniversalMaterial.STATIONARY_WATER.getType())){
		while(randBlock.getType().equals(UniversalMaterial.STATIONARY_WATER.getType()) && randBlock.getY() > 10){
			randBlock = randBlock.getRelative(0, -10, 0);
		}
		if(randBlock.getType().equals(Material.STONE)){
			return randBlock;
		}
	}
	
	// Find proper block nearby
	for(int i = -5; i<=5 ; i++){
		for(int j = -5; j<=5 ; j++){
			for(int k = -5; k<=5 ; k++){
				Block relativeBlock = randBlock.getRelative(i, j, k);
				if(relativeBlock.getType().equals(Material.STONE)){
					return relativeBlock;
				}
			}
		}
	}
	return null;
}
 
Example 15
Source File: TestCargoNodeListener.java    From Slimefun4 with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testNonCargoNode() {
    Player player = server.addPlayer();
    Location l = new Location(player.getWorld(), 190, 50, 400);
    Block b = l.getBlock();
    Block against = b.getRelative(BlockFace.DOWN);

    ItemStack item = new ItemStack(Material.PLAYER_HEAD);

    BlockPlaceEvent event = new BlockPlaceEvent(b, new BlockStateMock(), against, item, player, true, EquipmentSlot.HAND);
    listener.onCargoNodePlace(event);
    Assertions.assertFalse(event.isCancelled());
}
 
Example 16
Source File: BlockListener.java    From QuickShop-Reremake with GNU General Public License v3.0 4 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlace(BlockPlaceEvent e) {

    final Material type = e.getBlock().getType();
    final Block placingBlock = e.getBlock();
    final Player player = e.getPlayer();

    if (type != Material.CHEST) {
        return;
    }
    Block chest = null;
    //Chest combine mechanic based checking
    if (player.isSneaking()) {
        Block blockAgainst = e.getBlockAgainst();
        if (blockAgainst.getType() == Material.CHEST && placingBlock.getFace(blockAgainst) != BlockFace.UP && placingBlock.getFace(blockAgainst) != BlockFace.DOWN && !(((Chest) blockAgainst.getState()).getInventory() instanceof DoubleChestInventory)) {
            chest = e.getBlockAgainst();
        } else {
            return;
        }
    } else {
        //Get all chest in vertical Location
        BlockFace placingChestFacing = ((Directional) (placingBlock.getState().getBlockData())).getFacing();
        for (BlockFace face : Util.getVerticalFacing()) {
            //just check the right side and left side
            if (face != placingChestFacing && face != placingChestFacing.getOppositeFace()) {
                Block nearByBlock = placingBlock.getRelative(face);
                if (nearByBlock.getType() == Material.CHEST
                        //non double chest
                        && !(((Chest) nearByBlock.getState()).getInventory() instanceof DoubleChestInventory)
                        //same facing
                        && placingChestFacing == ((Directional) nearByBlock.getState().getBlockData()).getFacing()) {
                    if (chest == null) {
                        chest = nearByBlock;
                    } else {
                        //when multiply chests competed, minecraft will always combine with right side
                        if (placingBlock.getFace(nearByBlock) == Util.getRightSide(placingChestFacing)) {
                            chest = nearByBlock;
                        }
                    }
                }
            }
        }
    }
    if (chest == null) {
        return;
    }

    Shop shop = getShopPlayer(chest.getLocation(), false);
    if (shop != null) {
        if (!QuickShop.getPermissionManager().hasPermission(player, "quickshop.create.double")) {
            e.setCancelled(true);
            MsgUtil.sendMessage(player, MsgUtil.getMessage("no-double-chests", player));

        } else if (!shop.getModerator().isModerator(player.getUniqueId())) {
            e.setCancelled(true);
            MsgUtil.sendMessage(player, MsgUtil.getMessage("not-managed-shop", player));
        }
    }
}
 
Example 17
Source File: DoorManager.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
private static void toggleDoor(Block b) {
    if (b.getRelative(BlockFace.DOWN).getType().equals(b.getType())) {
        b = b.getRelative(BlockFace.DOWN);
    }
    RedProtect.get().getVersionHelper().toggleDoor(b);
}
 
Example 18
Source File: BlockDropsMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * This is not an event handler. It is called explicitly by BlockTransformListener
 * after all event handlers have been called.
 */
@SuppressWarnings("deprecation")
public void doBlockDrops(final BlockTransformEvent event) {
    if(!causesDrops(event.getCause())) {
        return;
    }

    final BlockDrops drops = event.getDrops();
    if(drops != null) {
        event.setCancelled(true);
        final BlockState oldState = event.getOldState();
        final BlockState newState = event.getNewState();
        final Block block = event.getOldState().getBlock();
        final int newTypeId = newState.getTypeId();
        final byte newData = newState.getRawData();

        block.setTypeIdAndData(newTypeId, newData, true);

        boolean explosion = false;
        MatchPlayer player = ParticipantBlockTransformEvent.getParticipant(event);

        if(event.getCause() instanceof EntityExplodeEvent) {
            EntityExplodeEvent explodeEvent = (EntityExplodeEvent) event.getCause();
            explosion = true;

            if(drops.fallChance != null &&
               oldState.getType().isBlock() &&
               oldState.getType() != Material.AIR &&
               this.getMatch().getRandom().nextFloat() < drops.fallChance) {

                FallingBlock fallingBlock = event.getOldState().spawnFallingBlock();
                fallingBlock.setDropItem(false);

                if(drops.landChance != null && this.getMatch().getRandom().nextFloat() >= drops.landChance) {
                    this.fallingBlocksThatWillNotLand.add(fallingBlock);
                }

                Vector v = fallingBlock.getLocation().subtract(explodeEvent.getLocation()).toVector();
                double distance = v.length();
                v.normalize().multiply(BASE_FALL_SPEED * drops.fallSpeed / Math.max(1d, distance));

                // A very simple deflection model. Check for a solid
                // neighbor block and "bounce" the velocity off of it.
                Block west = block.getRelative(BlockFace.WEST);
                Block east = block.getRelative(BlockFace.EAST);
                Block down = block.getRelative(BlockFace.DOWN);
                Block up = block.getRelative(BlockFace.UP);
                Block north = block.getRelative(BlockFace.NORTH);
                Block south = block.getRelative(BlockFace.SOUTH);

                if((v.getX() < 0 && west != null && Materials.isColliding(west.getType())) ||
                    v.getX() > 0 && east != null && Materials.isColliding(east.getType())) {
                    v.setX(-v.getX());
                }

                if((v.getY() < 0 && down != null && Materials.isColliding(down.getType())) ||
                    v.getY() > 0 && up != null && Materials.isColliding(up.getType())) {
                    v.setY(-v.getY());
                }

                if((v.getZ() < 0 && north != null && Materials.isColliding(north.getType())) ||
                    v.getZ() > 0 && south != null && Materials.isColliding(south.getType())) {
                    v.setZ(-v.getZ());
                }

                fallingBlock.setVelocity(v);
            }
        }

        dropObjects(drops, player, newState.getLocation(), 1d, explosion);

    }
}
 
Example 19
Source File: Kitchen.java    From ExoticGarden with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onInteract(Player p, Block b) {
    Block dispenser = b.getRelative(BlockFace.DOWN);

    Furnace furnace = locateFurnace(dispenser);
    FurnaceInventory furnaceInventory = furnace.getInventory();

    Inventory inv = ((Dispenser) dispenser.getState()).getInventory();
    List<ItemStack[]> inputs = RecipeType.getRecipeInputList(this);

    recipe:
    for (ItemStack[] input : inputs) {
        for (int i = 0; i < inv.getContents().length; i++) {
            if (!SlimefunUtils.isItemSimilar(inv.getContents()[i], input[i], true)) continue recipe;
        }

        ItemStack adding = RecipeType.getRecipeOutputList(this, input);

        if (Slimefun.hasUnlocked(p, adding, true)) {
            boolean canFit = furnaceInventory.getResult() == null || (furnaceInventory.getResult().getAmount() + adding.getAmount() <= 64 && SlimefunUtils.isItemSimilar(furnaceInventory.getResult(), adding, true));

            if (!canFit) {
                SlimefunPlugin.getLocal().sendMessage(p, "machines.full-inventory", true);
                return;
            }

            for (int i = 0; i < inv.getContents().length; i++) {
                ItemStack item = inv.getItem(i);

                if (item != null) {
                    ItemUtils.consumeItem(item, item.getType() == Material.MILK_BUCKET);
                }
            }

            Bukkit.getScheduler().runTaskLater(plugin, () -> p.getWorld().playSound(furnace.getLocation(), Sound.BLOCK_LAVA_EXTINGUISH, 1F, 1F), 55L);

            for (int i = 1; i < 7; i++) {
                Bukkit.getScheduler().runTaskLater(plugin, () -> p.getWorld().playSound(furnace.getLocation(), Sound.BLOCK_METAL_PLACE, 7F, 1F), i * 5L);
            }

            if (furnaceInventory.getResult() == null) {
                furnaceInventory.setResult(adding);
            }
            else {
                furnaceInventory.getResult().setAmount(furnaceInventory.getResult().getAmount() + adding.getAmount());
            }
        }

        return;
    }

    SlimefunPlugin.getLocal().sendMessage(p, "machines.pattern-not-found", true);
}
 
Example 20
Source File: ExtensionLobbyWall.java    From HeavySpleef with GNU General Public License v3.0 4 votes vote down vote up
public static SignRow generateRow(Sign clicked) {
	Block block = clicked.getBlock();
	Location location = block.getLocation();
	Block attachedOn = getAttached(clicked);
	
	Location mod = attachedOn.getLocation().subtract(location);
	BlockFace2D dir = BlockFace2D.byVector2D(mod.getBlockX(), mod.getBlockZ());
	
	BlockFace2D leftDir = dir.left();
	BlockFace2D rightDir = dir.right();
	
	BlockFace leftFace = leftDir.getBlockFace3D();
	BlockFace rightFace = rightDir.getBlockFace3D();
	
	Location start = location;
	Block lastBlock = block;
	
	while (true) {
		Block leftBlock = lastBlock.getRelative(leftFace);
		if (leftBlock.getType() != Material.WALL_SIGN) {
			break;
		}
		
		lastBlock = leftBlock;
		start = leftBlock.getLocation();
	}
	
	Location end = location;
	lastBlock = block;
	
	while (true) {
		Block rightBlock = lastBlock.getRelative(rightFace);
		if (rightBlock.getType() != Material.WALL_SIGN) {
			break;
		}
		
		lastBlock = rightBlock;
		end = rightBlock.getLocation();
	}
	
	try {
		return new SignRow(clicked.getWorld(), start.toVector(), end.toVector());
	} catch (SignRowValidationException e) {
		throw new RuntimeException(e);
	}
}