Java Code Examples for org.bukkit.World#getBlockAt()

The following examples show how to use org.bukkit.World#getBlockAt() . 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: BlockEventTracker.java    From GriefDefender with MIT License 6 votes vote down vote up
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onBlockFalling(EntitySpawnEvent event) {
    final Entity entity = event.getEntity();
    final World world = entity.getWorld();
    if (entity instanceof FallingBlock) {
        // add owner
        final Location location = entity.getLocation();
        final Block block = world.getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ());
        final GDClaimManager claimWorldManager = GriefDefenderPlugin.getInstance().dataStore.getClaimWorldManager(location.getWorld().getUID());
        final GDChunk gdChunk = claimWorldManager.getChunk(location.getChunk());
        final UUID ownerUniqueId = gdChunk.getBlockOwnerUUID(block.getLocation());
        if (ownerUniqueId != null) {
            final GDEntity gdEntity = new GDEntity(event.getEntity().getEntityId());
            gdEntity.setOwnerUUID(ownerUniqueId);
            gdEntity.setNotifierUUID(ownerUniqueId);
            EntityTracker.addTempEntity(gdEntity);
        }
    }
}
 
Example 2
Source File: JoinSign.java    From DungeonsXL with GNU General Public License v3.0 6 votes vote down vote up
protected JoinSign(DungeonsXL plugin, World world, int id, ConfigurationSection config) {
    super(plugin, world, id);

    startSign = world.getBlockAt(config.getInt("x"), config.getInt("y"), config.getInt("z"));
    String identifier = config.getString("dungeon");
    dungeon = plugin.getDungeonRegistry().get(identifier);

    // LEGACY
    if (config.contains("maxElements")) {
        maxElements = config.getInt("maxElements");
    } else if (config.contains("maxGroupsPerGame")) {
        maxElements = config.getInt("maxGroupsPerGame");
    } else if (config.contains("maxPlayersPerGroup")) {
        maxElements = config.getInt("maxPlayersPerGroup");
    }
    startIfElementsAtLeast = config.getInt("startIfElementsAtLeast", -1);

    verticalSigns = (int) Math.ceil((float) (1 + maxElements) / 4);

    update();
}
 
Example 3
Source File: Lobby.java    From UhcCore with GNU General Public License v3.0 6 votes vote down vote up
public void destroyBoundingBox(){
	if(built){
		int lobbyX = loc.getBlockX(), lobbyY = loc.getBlockY()+2, lobbyZ = loc.getBlockZ();
		
		World world = loc.getWorld();
		for(int x = -width; x <= width; x++){
			for(int y = height; y >= -height; y--){
				for(int z = -length ; z <= length ; z++){
					Block block = world.getBlockAt(lobbyX+x,lobbyY+y,lobbyZ+z);
					if(!block.getType().equals(Material.AIR)){
						block.setType(Material.AIR);
					}
				}
			}
		}
	}
}
 
Example 4
Source File: SignShop.java    From Shopkeepers with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void delete() {
	World world = Bukkit.getWorld(shopkeeper.getWorldName());
	if (world != null) {
		// this should load the chunk if necessary, making sure that the block gets removed (though, might not work
		// on server stops..):
		Block signBlock = world.getBlockAt(shopkeeper.getX(), shopkeeper.getY(), shopkeeper.getZ());
		if (Utils.isSign(signBlock.getType())) {
			// remove sign:
			signBlock.setType(Material.AIR);
		}
		// TODO trigger an unloadChunkRequest if the chunk had to be loaded? (for now let's assume that the server
		// handles that kind of thing automatically)
	} else {
		// well: world unloaded and we didn't get an event.. not our fault
		// TODO actually, we are not removing the sign on world unloads..
	}
}
 
Example 5
Source File: TilesCustomNBTPersistentTest.java    From Item-NBT-API with MIT License 6 votes vote down vote up
@Override
public void test() throws Exception {
	if(MinecraftVersion.getVersion().getVersionId() < MinecraftVersion.MC1_14_R1.getVersionId())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);
				NBTTileEntity comp = new NBTTileEntity(block.getState());
				NBTCompound persistentData = comp.getPersistentDataContainer();
				persistentData.setString("Foo", "Bar");
				if (!new NBTTileEntity(block.getState()).getPersistentDataContainer().toString().contains("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: LobbyListener.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void signRemoved(BlockBreakEvent event) {
	if (Util.get().isSpawnWorld(event.getBlock().getWorld())) {
		 Location blockLocation = event.getBlock().getLocation();
	        World w = blockLocation.getWorld();
	    	Block b = w.getBlockAt(blockLocation);
			if(b.getType() == Material.WALL_SIGN || b.getType() == SkyWarsReloaded.getNMS().getMaterial("SIGN_POST").getType()){
		    	Sign sign = (Sign) b.getState();
		    	Location loc = sign.getLocation();
		    	boolean removed = false;
		    	for (GameMap gMap : GameMap.getMaps()) {
		    		if (!removed) {
			    		removed = gMap.removeSign(loc);
		    		}
		    	}
		    	if (!removed) {
		    		removed = SkyWarsReloaded.getLB().removeLeaderSign(loc);
		    	}
		    	if (removed) {
			    	event.getPlayer().sendMessage(new Messaging.MessageFormatter().format("signs.remove"));
		    	}
			}
	}
}
 
Example 7
Source File: AdminRebuild.java    From Modern-LWC with MIT License 6 votes vote down vote up
/**
 * Look for a protectable block in each world. Return the first one found. Starts in the main world.
 *
 * @param x
 * @param y
 * @param z
 * @return
 */
private Block findProtectableBlock(int x, int y, int z) {
    LWC lwc = LWC.getInstance();
    Server server = Bukkit.getServer();

    for (World world : server.getWorlds()) {
        Block block = world.getBlockAt(x, y, z);

        if (lwc.isProtectable(block)) {
            // Woo!
            return block;
        }
    }

    // Bad news...
    return null;
}
 
Example 8
Source File: LaneMatchModule.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Vector getSafeLocationUnder(Block block) {
    World world = block.getWorld();
    for(int y = block.getY() - 2; y >= 0; y--) {
        Block feet = world.getBlockAt(block.getX(), y, block.getZ());
        Block head = world.getBlockAt(block.getX(), y + 1, block.getZ());
        if(feet.getType() == Material.AIR && head.getType() == Material.AIR) {
            return new Vector(block.getX() + 0.5, y, block.getZ() + 0.5);
        }
    }
    return new Vector(block.getX() + 0.5, -2, block.getZ() + 0.5);
}
 
Example 9
Source File: ChunkGenerator.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tests if the specified location is valid for a natural spawn position
 *
 * @param world The world we're testing on
 * @param x     X-coordinate of the block to test
 * @param z     Z-coordinate of the block to test
 * @return true if the location is valid, otherwise false
 */
public boolean canSpawn(World world, int x, int z) {
    Block highest = world.getBlockAt(x, world.getHighestBlockYAt(x, z), z);

    switch (world.getEnvironment()) {
        case NETHER:
            return true;
        case THE_END:
            return highest.getType() != Material.AIR && highest.getType() != Material.WATER && highest.getType() != Material.LAVA;
        case NORMAL:
        default:
            return highest.getType() == Material.SAND || highest.getType() == Material.GRAVEL;
    }
}
 
Example 10
Source File: SchematicUtil.java    From PlotMe-Core with GNU General Public License v3.0 5 votes vote down vote up
private org.bukkit.entity.Entity getLeash(IWorld world1, Leash leash, com.worldcretornica.plotme_core.api.Vector loc, int originX, int originY,
        int originZ) {
    org.bukkit.entity.Entity ent = null;
    World world = ((BukkitWorld) world1).getWorld();

    int x = leash.getX() - originX;
    int y = leash.getY() - originY;
    int z = leash.getZ() - originZ;

    org.bukkit.Location etloc = new org.bukkit.Location(world, x + loc.getBlockX(), y + loc.getBlockY(), z + loc.getBlockZ());

    Block block = world.getBlockAt(etloc);

    if (block.getType() == Material.FENCE || block.getType() == Material.NETHER_FENCE) {
        etloc.setX(Math.floor(etloc.getX()));
        etloc.setY(Math.floor(etloc.getY()));
        etloc.setZ(Math.floor(etloc.getZ()));

        ent = world.spawnEntity(etloc, EntityType.LEASH_HITCH);

        List<org.bukkit.entity.Entity> nearbyentities = ent.getNearbyEntities(1, 1, 1);

        for (org.bukkit.entity.Entity nearby : nearbyentities) {
            if (nearby instanceof LeashHitch) {
                if (nearby.getLocation().distance(ent.getLocation()) == 0) {
                    ent.remove();
                    return nearby;
                }
            }
        }
    }

    return ent;
}
 
Example 11
Source File: LeaveSign.java    From DungeonsXL with GNU General Public License v3.0 5 votes vote down vote up
public LeaveSign(DungeonsXL plugin, World world, int id, ConfigurationSection config) {
    super(plugin, world, id);

    sign = world.getBlockAt(config.getInt("x"), config.getInt("y"), config.getInt("z"));
    setText();

    LWCUtil.removeProtection(sign);
}
 
Example 12
Source File: BlockFromToListener.java    From IridiumSkyblock with GNU General Public License v2.0 5 votes vote down vote up
public boolean isSurroundedByWater(Location location) {
    final World world = location.getWorld();
    if (world == null) return false;
    final int x = location.getBlockX();
    final int y = location.getBlockY();
    final int z = location.getBlockZ();
    final int[][] coords = {
            // At the same elevation
            {x + 1, y, z},
            {x - 1, y, z},
            {x, y, z + 1},
            {x, y, z - 1},
            // Above
            {x + 1, y + 1, z},
            {x - 1, y + 1, z},
            {x, y + 1, z + 1},
            {x, y + 1, z - 1},
            // Below
            {x + 1, y - 1, z},
            {x - 1, y - 1, z},
            {x, y - 1, z + 1},
            {x, y - 1, z - 1}
    };
    for (int[] coord : coords) {
        final Block block = world.getBlockAt(coord[0], coord[1], coord[2]);
        final Material material = block.getType();
        final String name = material.name();
        if (name.contains("WATER")) return true;
    }
    return false;
}
 
Example 13
Source File: MergeTileSubCompoundTest.java    From Item-NBT-API with MIT License 5 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 {
			boolean failed = false;
			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.addCompound("subcomp").setString("hello", "world");
				NBTContainer cont = new NBTContainer();
				cont.mergeCompound(comp.getCompound("subcomp"));
				if (!(cont.hasKey("hello") && "world".equals(cont.getString("hello")))) {
					failed = true;
				}
				block.setType(Material.AIR);
				if(failed) {
					throw new NbtApiException("Data was not correct! " + cont);
				}
			}
		} catch (Exception ex) {
			throw new NbtApiException("Wasn't able to use NBTTiles!", ex);
		}
	}
}
 
Example 14
Source File: TpCommand.java    From MarriageMaster with GNU General Public License v3.0 5 votes vote down vote up
private @Nullable Location getSaveLoc(@NotNull Location loc)
{
	Material mat, matB1, matB2;
	World w = loc.getWorld();
	if(w == null) return null;
	int y = loc.getBlockY(), i;
	if(loc.getY() - y < 0.001) y--;
	int x = loc.getBlockX(), z = loc.getBlockZ(), miny = Math.max(y - 10, 1);
	Block b, b1 = w.getBlockAt(x, y + 1, z), b2 = w.getBlockAt(x, y + 2, z);
	matB1 = b1 == null ? Material.AIR : b1.getType();
	matB2 = b2 == null ? Material.AIR : b1.getType();
	for(loc = null, i = 0; y > 0 && y > miny && loc == null; y--, i++)
	{
		b = w.getBlockAt(x, y, z);
		mat = b == null ? Material.AIR : b.getType();
		if(b != null && !b.isEmpty())
		{
			if((!BAD_MATS.contains(mat) && mat != Material.AIR) &&
					(b1 == null || (MCVersion.isNewerOrEqualThan(MCVersion.MC_1_13) ? (b1.isPassable() && !BAD_MATS.contains(matB1)) : b1.isEmpty())) &&
					(b2 == null || (MCVersion.isNewerOrEqualThan(MCVersion.MC_1_13) ? (b2.isPassable() && !BAD_MATS.contains(matB2)) : b2.isEmpty())))
			{
				loc = b.getLocation();
				loc.setX(loc.getX() + 0.5);
				loc.setY(loc.getY() + 1);
				loc.setZ(loc.getZ() + 0.5);
			}
		}
		b2 = b1;
		matB2 = matB1;
		b1 = b;
		matB1 = mat;
	}
	return loc;
}
 
Example 15
Source File: SignListener.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
  public void signRemoved(BlockBreakEvent event) {
      Location blockLocation = event.getBlock().getLocation();
      World w = blockLocation.getWorld();
  	Block b = w.getBlockAt(blockLocation);
if(b.getType() == Material.WALL_SIGN || b.getType() == SkyWarsReloaded.getNMS().getMaterial("SIGN_POST").getType()){
   	Sign sign = (Sign) b.getState();
   	Location loc = sign.getLocation();
   	SWRServer server = SWRServer.getSign(loc);
   	if (server != null) {
   		server.removeSign(loc);
   		event.getPlayer().sendMessage(new Messaging.MessageFormatter().format("signs.remove"));
   	}
}
  }
 
Example 16
Source File: EconomyManager.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public static long getRegionValue(Region r) {
    long regionCost = 0;
    World w = RedProtect.get().getServer().getWorld(r.getWorld());
    int maxX = r.getMaxMbrX();
    int minX = r.getMinMbrX();
    int maxZ = r.getMaxMbrZ();
    int minZ = r.getMinMbrZ();
    int factor;
    for (int x = minX; x < maxX; x++) {
        for (int y = 0; y < 256; y++) {
            for (int z = minZ; z < maxZ; z++) {

                Block b = w.getBlockAt(x, y, z);
                if (b.isEmpty()) {
                    continue;
                }

                if (b.getState() instanceof InventoryHolder) {
                    Inventory inv = ((InventoryHolder) b.getState()).getInventory();

                    if (inv.getSize() == 54) {
                        factor = 2;
                    } else {
                        factor = 1;
                    }

                    for (ItemStack item : inv.getContents()) {
                        if (item == null || item.getAmount() == 0) {
                            continue;
                        }
                        regionCost = regionCost + ((RedProtect.get().config.ecoRoot().items.values.getOrDefault(item.getType().name(), 0L) * item.getAmount()) / factor);
                        if (item.getEnchantments().size() > 0) {
                            for (Enchantment enchant : item.getEnchantments().keySet()) {
                                regionCost = regionCost + ((RedProtect.get().config.ecoRoot().enchantments.values.getOrDefault(enchant.getName(), 0L) * item.getEnchantments().get(enchant)) / factor);
                            }
                        }
                    }
                } else {
                    regionCost = regionCost + RedProtect.get().config.ecoRoot().items.values.getOrDefault(b.getType().name(), 0L);
                }
            }
        }
    }
    return regionCost;
}
 
Example 17
Source File: BlockUtils.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
public static Block blockAt(World world, Vector pos) {
    return world.getBlockAt(pos.getBlockX(),
                            pos.getBlockY(),
                            pos.getBlockZ());
}
 
Example 18
Source File: WarehouseEffect.java    From Civs with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void regionCreatedHandler(Region r) {
    if (!r.getEffects().containsKey(KEY)) {
        return;
    }

    ArrayList<CVInventory> chests = new ArrayList<>();
    chests.add(UnloadedInventoryHandler.getInstance().getChestInventory(r.getLocation()));

    RegionType rt = (RegionType) ItemManager.getInstance().getItemType(r.getType());
    double lx = Math.floor(r.getLocation().getX()) + 0.4;
    double ly = Math.floor(r.getLocation().getY()) + 0.4;
    double lz = Math.floor(r.getLocation().getZ()) + 0.4;
    double buildRadius = rt.getBuildRadius();

    int x = (int) Math.round(lx - buildRadius);
    int y = (int) Math.round(ly - buildRadius);
    y = y < 0 ? 0 : y;
    int z = (int) Math.round(lz - buildRadius);
    int xMax = (int) Math.round(lx + buildRadius);
    int yMax = (int) Math.round(ly + buildRadius);
    World world = r.getLocation().getWorld();
    if (world != null) {
        yMax = yMax > world.getMaxHeight() - 1 ? world.getMaxHeight() - 1 : yMax;
        int zMax = (int) Math.round(lz + buildRadius);

        for (int i = x; i < xMax; i++) {
            for (int j = y; j < yMax; j++) {
                for (int k = z; k < zMax; k++) {
                    Block block = world.getBlockAt(i, j, k);

                    if (block.getType() == Material.CHEST) {
                        chests.add(UnloadedInventoryHandler.getInstance().getChestInventory(block.getLocation()));
                    }
                }
            }
        }
    }


    File dataFolder = new File(Civs.dataLocation, Constants.REGIONS);
    if (!dataFolder.exists()) {
        return;
    }
    File dataFile = new File(dataFolder, r.getId() + ".yml");
    if (!dataFile.exists()) {
        Civs.logger.log(Level.SEVERE, "Warehouse region file does not exist {0}.yml", r.getId());
        return;
    }
    FileConfiguration config = new YamlConfiguration();
    try {
        config.load(dataFile);
        ArrayList<String> locationList = new ArrayList<>();
        for (CVInventory cvInventory : chests) {
            locationList.add(Region.blockLocationToString(cvInventory.getLocation()));
        }
        config.set(Constants.CHESTS, locationList);
        config.save(dataFile);
    } catch (Exception e) {
        e.printStackTrace();
        Civs.logger.log(Level.WARNING, UNABLE_TO_SAVE_CHEST, r.getId());
        return;
    }
    checkExcessChests(r);
}
 
Example 19
Source File: ContainerManager.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public boolean canOpen(Block b, Player p) {
    if (!RedProtect.get().config.configRoot().private_cat.use || p.hasPermission("redprotect.bypass")) {
        return true;
    }

    String blocktype = b.getType().name();
    List<String> blocks = RedProtect.get().config.configRoot().private_cat.allowed_blocks;

    boolean deny = true;
    if (blocks.stream().anyMatch(blocktype::matches)) {
        int x = b.getX();
        int y = b.getY();
        int z = b.getZ();
        World w = p.getWorld();

        for (int sx = -1; sx <= 1; sx++) {
            for (int sz = -1; sz <= 1; sz++) {
                Block bs = w.getBlockAt(x + sx, y, z + sz);
                if (isSign(bs) && (validatePrivateSign(bs))) {
                    deny = false;
                    if (validateOpenBlock(bs, p)) {
                        return true;
                    }
                }

                int x2 = bs.getX();
                int y2 = bs.getY();
                int z2 = bs.getZ();

                String blocktype2 = b.getType().name();
                if (blocks.stream().anyMatch(blocktype2::matches)) {
                    for (int ux = -1; ux <= 1; ux++) {
                        for (int uz = -1; uz <= 1; uz++) {
                            Block bu = w.getBlockAt(x2 + ux, y2, z2 + uz);
                            if (isSign(bu) && (validatePrivateSign(bu))) {
                                deny = false;
                                if (validateOpenBlock(bu, p)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return deny;
}
 
Example 20
Source File: ContainerManager.java    From RedProtect with GNU General Public License v3.0 4 votes vote down vote up
public boolean canWorldBreak(Block b) {
    if (!RedProtect.get().config.configRoot().private_cat.use) {
        return true;
    }
    Region reg = RedProtect.get().rm.getTopRegion(b.getLocation());
    if (reg == null && !RedProtect.get().config.configRoot().private_cat.allow_outside) {
        return true;
    }
    int x = b.getX();
    int y = b.getY();
    int z = b.getZ();
    World w = b.getWorld();

    if (isSign(b) && validWorldBreak(b)) {
        RedProtect.get().logger.debug(LogLevel.DEFAULT, "Valid Sign on canWorldBreak!");
        return false;
    }

    String signbtype = b.getType().name();
    List<String> blocks = RedProtect.get().config.configRoot().private_cat.allowed_blocks;

    if (blocks.stream().anyMatch(signbtype::matches)) {
        for (int sx = -1; sx <= 1; sx++) {
            for (int sz = -1; sz <= 1; sz++) {
                Block bs = w.getBlockAt(x + sx, y, z + sz);
                if (isSign(bs) && validWorldBreak(bs)) {
                    return false;
                }

                String blocktype2 = b.getType().name();

                int x2 = bs.getX();
                int y2 = bs.getY();
                int z2 = bs.getZ();

                if (blocks.stream().anyMatch(blocktype2::matches)) {
                    for (int ux = -1; ux <= 1; ux++) {
                        for (int uz = -1; uz <= 1; uz++) {
                            Block bu = w.getBlockAt(x2 + ux, y2, z2 + uz);
                            if (isSign(bu) && validWorldBreak(bu)) {
                                return false;
                            }
                        }
                    }
                }
            }
        }
    }
    return true;
}