org.bukkit.World Java Examples

The following examples show how to use org.bukkit.World. 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: CitizensShop.java    From Shopkeepers with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void onInit() {
	super.onInit();
	if (this.isActive()) return;
	if (!CitizensHandler.isEnabled()) return;

	// create npc:
	EntityType entityType;
	String name;
	if (shopkeeper.getType().isPlayerShopType()) {
		// player shops will use a player npc:
		entityType = EntityType.PLAYER;
		name = ((PlayerShopkeeper) shopkeeper).getOwnerName();
	} else {
		entityType = EntityType.VILLAGER;
		name = "Shopkeeper";
	}

	// prepare location:
	World world = Bukkit.getWorld(shopkeeper.getWorldName());
	Location location = new Location(world, shopkeeper.getX() + 0.5D, shopkeeper.getY() + 0.5D, shopkeeper.getZ() + 0.5D);

	// create npc:
	npcId = CitizensHandler.createNPC(location, entityType, name);
}
 
Example #2
Source File: MatchImpl.java    From PGM with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void destroy() {
  if (isLoaded()) {
    logger.log(
        Level.SEVERE,
        "Match " + getId() + " is being destroyed without having previously been unloaded");
    unload();
  }

  World world = getWorld();
  this.world.clear();
  if (world == null) return;

  final String worldName = world.getName();
  if (PGM.get().getServer().unloadWorld(worldName, false)) {
    logger.fine("Successfully unloaded " + worldName);
  } else {
    logger.log(
        Level.SEVERE, "Unable to unload world " + worldName + " (this can cause memory leaks!)");
  }

  final File oldMatchFolder = new File(PGM.get().getServer().getWorldContainer(), worldName);
  if (oldMatchFolder.exists()) {
    FileUtils.delete(oldMatchFolder);
  }
}
 
Example #3
Source File: CustomTimingsHandler.java    From Kettle with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Prints the timings and extra data to the given stream.
 *
 * @param printStream
 */
public static void printTimings(PrintStream printStream) {
    printStream.println("Minecraft");
    for (CustomTimingsHandler timings : HANDLERS) {
        long time = timings.totalTime;
        long count = timings.count;
        if (count == 0) {
            continue;
        }
        long avg = time / count;

        printStream.println("    " + timings.name + " Time: " + time + " Count: " + count + " Avg: " + avg + " Violations: " + timings.violations);
    }
    printStream.println("# Version " + Bukkit.getVersion());
    int entities = 0;
    int livingEntities = 0;
    for (World world : Bukkit.getWorlds()) {
        entities += world.getEntities().size();
        livingEntities += world.getLivingEntities().size();
    }
    printStream.println("# Entities " + entities);
    printStream.println("# LivingEntities " + livingEntities);
}
 
Example #4
Source File: SignListener.java    From SkyWarsReloaded with GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void signPlaced(SignChangeEvent event) {
    String[] lines = event.getLines();
    if (lines[0].equalsIgnoreCase("[sw]") && lines.length >= 2) {
    	if (event.getPlayer().hasPermission("sw.signs")) {
    			Location signLocation = event.getBlock().getLocation();
                World w = signLocation.getWorld();
            	Block b = w.getBlockAt(signLocation);
            	if(b.getType() == Material.WALL_SIGN || b.getType() == SkyWarsReloaded.getNMS().getMaterial("SIGN_POST").getType()) {
           			event.setCancelled(true);
           			String serverName = lines[1];
           			SWRServer server = SWRServer.getServer(serverName);
           			if (server != null) {
           				server.addSign(signLocation);
                   		event.getPlayer().sendMessage(new Messaging.MessageFormatter().format("signs.added"));
                   	} else {
                   		event.getPlayer().sendMessage(new Messaging.MessageFormatter().format("signs.no-map"));
                   	}
            	}
        	} else {
        		event.getPlayer().sendMessage(new Messaging.MessageFormatter().format("error.signs-no-perm"));
    			event.setCancelled(true);
        } 
   }
}
 
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: ArenaManager.java    From civcraft with GNU General Public License v2.0 6 votes vote down vote up
private static World createArenaWorld(ConfigArena arena, String name) {
	World world;
	world = Bukkit.getServer().getWorld(name);
	if (world == null) {
		WorldCreator wc = new WorldCreator(name);
		wc.environment(Environment.NORMAL);
		wc.type(WorldType.FLAT);
		wc.generateStructures(false);
		
		world = Bukkit.getServer().createWorld(wc);
		world.setAutoSave(false);
		world.setSpawnFlags(false, false);
		world.setKeepSpawnInMemory(false);
		ChunkCoord.addWorld(world);
	}
	
	return world;
}
 
Example #7
Source File: HarborCommand.java    From Harbor with MIT License 5 votes vote down vote up
@Override
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
    final String prefix = Config.getString("messages.miscellaneous.chat-prefix");

    if (args.length < 1 || !sender.hasPermission("harbor.admin")) {
        sender.sendMessage(ChatColor.translateAlternateColorCodes('&', String.format(
                "%sHarbor version %s by TechToolbox (@nkomarn).", prefix, Harbor.version)));
    } else if (args[0].equalsIgnoreCase("reload")) {
        Harbor.getHarbor().reloadConfig();
        sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix
                + "Reloaded configuration."));
    } else if (args[0].equalsIgnoreCase("forceskip")) {
        if (!(sender instanceof Player)) {
            sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix
                    + "This command requires you to be a player."));
        } else {
            Player player = (Player) sender;
            World world = player.getWorld();

            if (Checker.SKIPPING_WORLDS.contains(world)) {
                sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix
                        + "This world's time is already being accelerated."));
            } else {
                Checker.SKIPPING_WORLDS.add(world);
                new AccelerateNightTask(world).runTaskTimer(Harbor.getHarbor(), 0L, 1);
                sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix
                        + "Forcing night skip in your world."));
            }
        }
    } else {
        sender.sendMessage(ChatColor.translateAlternateColorCodes('&', prefix
                + Config.getString("messages.miscellaneous.unrecognized-command")));
    }
    return true;
}
 
Example #8
Source File: Holograms.java    From HubBasics with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Get the location of given hologram
 *
 * @param hologram The ID of the hologram
 * @return Location of hologram
 */
public Location getLocation(int hologram) {
    JSONObject object = new JSONObject(file.getString("hologram." + hologram + ".location"));
    double x = object.getDouble("x");
    double y = object.getDouble("y");
    double z = object.getDouble("z");
    World world = Bukkit.getWorld(object.getString("w"));
    return new Location(world, x, y, z);
}
 
Example #9
Source File: WorldManager.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the given {@link World} is the skyblock island world.
 * @param world World to check.
 * @return True if the given world is the skyblock island world, false otherwise.
 */
public boolean isSkyWorld(@Nullable World world) {
    if (world == null) {
        return false;
    }

    return getWorld().getName().equalsIgnoreCase(world.getName());
}
 
Example #10
Source File: WorldConfig.java    From GlobalWarming with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String getDisplayName(UUID worldId) {
    String worldName = "UNKNOWN";
    if (worldId != null) {
        World world = Bukkit.getWorld(worldId);
        if (world != null) {
            worldName = world.getName();
        }
    }

    return worldName;
}
 
Example #11
Source File: NMSHandler.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void spawnDragon(World world, Location loc) {
	WorldServer w = ((CraftWorld) world).getHandle();
	EntityEnderDragon dragon = new EntityEnderDragon(w);
	dragon.getDragonControllerManager().setControllerPhase(DragonControllerPhase.c);
	dragon.setLocation(loc.getX(), loc.getY(), loc.getZ(), w.random.nextFloat() * 360.0F, 0.0F);
	w.addEntity(dragon);
}
 
Example #12
Source File: ExprLocationAt.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "null"})
@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
	x = (Expression<Number>) exprs[0];
	y = (Expression<Number>) exprs[1];
	z = (Expression<Number>) exprs[2];
	world = (Expression<World>) exprs[3];
	return true;
}
 
Example #13
Source File: LocationSerializer.java    From PerWorldInventory with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Deserialize a location from a given JsonObject.
 *
 * @param loc The JsonObject to deserialize
 * @return The Location
 */
public static Location deserialize(JsonObject loc) {
    String worldName = loc.get("world").getAsString();
    World world = Bukkit.getWorld(worldName);
    double x = loc.get("x").getAsDouble();
    double y = loc.get("y").getAsDouble();
    double z = loc.get("z").getAsDouble();
    float pitch = loc.get("pitch").getAsFloat();
    float yaw = loc.get("yaw").getAsFloat();

    return new Location(world, x, y, z, yaw, pitch);
}
 
Example #14
Source File: EvtAtTime.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
void execute(final World w) {
	final Trigger t = this.t;
	if (t == null) {
		assert false;
		return;
	}
	final ScheduledEvent e = new ScheduledEvent(w);
	SkriptEventHandler.logEventStart(e);
	SkriptEventHandler.logTriggerEnd(t);
	t.execute(e);
	SkriptEventHandler.logTriggerEnd(t);
	SkriptEventHandler.logEventEnd();
}
 
Example #15
Source File: BukkitModule.java    From intake with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void configure() {
  bind(CommandSender.class).toProvider(new CommandSenderProvider());
  bind(Player.class).annotatedWith(Sender.class).toProvider(new ProvidedPlayerProvider());
  bind(Player.class).toProvider(new DynamicPlayerProvider());
  bind(World.class).toProvider(new WorldProvider());
}
 
Example #16
Source File: SpawnEventsTest.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void onPhantomSpawn_overworldNotAllowed() {
    when(worldManager.isSkyWorld(any(World.class))).thenReturn(true);

    CreatureSpawnEvent event = new CreatureSpawnEvent(getFakePhantom(),
            CreatureSpawnEvent.SpawnReason.NATURAL);
    spawnEvents.setPhantomsInOverworld(false);
    spawnEvents.onPhantomSpawn(event);

    assertTrue(event.isCancelled());
}
 
Example #17
Source File: EffPvP.java    From Skript with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "null"})
@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
	worlds = (Expression<World>) exprs[0];
	enable = matchedPattern == 0;
	return true;
}
 
Example #18
Source File: GameMap.java    From AnnihilationPro with MIT License 5 votes vote down vote up
public void unLoadMap()
	{
		//World tpworld = Bukkit.getWorlds().size() > 0 ? Bukkit.getWorlds().get(0) : null;
		World tpworld = Game.LobbyMap != null ? Game.LobbyMap.getWorld() : null;
		if(tpworld == null)
			tpworld = Bukkit.getWorlds().size() > 0 ? Bukkit.getWorlds().get(0) : null;
		for(Player p : Bukkit.getOnlinePlayers())
		{
			if(p.getWorld().getName().equals(this.getWorldName()))
			{
				if(tpworld != null)
					p.teleport(tpworld.getSpawnLocation());
				else
					p.kickPlayer("Unloading the world and we dont want you to get trapped or glitched!");
			}
		}
		this.unregisterListeners();

		boolean b = Bukkit.unloadWorld(super.getWorldName(), false);
        Bukkit.getLogger().info("[Annihilation] "+super.getNiceWorldName()+" was unloaded successfully: "+b);
//		try
//		{
//			FileUtils.deleteDirectory(this.mapDirec);
//			FileUtils.copyDirectory(this.tempDirec, this.mapDirec);
//			FileUtils.deleteDirectory(this.tempDirec);
//		}
//		catch (IOException e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
	}
 
Example #19
Source File: MobSpawnEvent.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void doEvent() {
	if (gMap.getMatchState() == MatchState.PLAYING) {
		this.fired = true;
		sendTitle();
		World world = gMap.getCurrentWorld();
		for (int i = 0; i < gMap.getAlivePlayers().size(); i++) {
			Player player = gMap.getAlivePlayers().get(i);
			br1 = new BukkitRunnable() {
				@Override
				public void run() {
					if (player != null) {
						List<Block> blocks = getSpawnableBlocks(player.getLocation());
						Collections.shuffle(blocks);
						for (int i = 0; i < Util.get().getRandomNum(minMobsPerPlayer, maxMobsPerPlayer); i++) {
							Location spawn = blocks.get(i).getLocation().clone().add(0, 1, 0);
							LivingEntity ent = (LivingEntity) world.spawnEntity(spawn, EntityType.valueOf(mobs.get(ThreadLocalRandom.current().nextInt(0, mobs.size())).toUpperCase()));
							if (ent instanceof Zombie || ent instanceof Skeleton) {
								ent.getEquipment().setHelmet(new ItemStack(Material.CHAINMAIL_HELMET, 1));
							}
							SkyWarsReloaded.getNMS().setEntityTarget(ent, player);
							mobsSpawned.add(ent);
						}
					}
				}
			}.runTaskLater(SkyWarsReloaded.get(), i * 3L);
		}
		if (length != -1) {
			br2 = new BukkitRunnable() {
				@Override
				public void run() {
					endEvent(false);
				}
			}.runTaskLater(SkyWarsReloaded.get(), length * 20L);
		}
	}
}
 
Example #20
Source File: DifficultyModule.java    From UHC with MIT License 5 votes vote down vote up
@Override
public void onEnable() {
    for (final World world : Bukkit.getWorlds()) {
        if (worlds.worldMatches(world)) {
            world.setDifficulty(Difficulty.HARD);
        }
    }
}
 
Example #21
Source File: Reflections.java    From FunnyGuilds with Apache License 2.0 5 votes vote down vote up
public static Object getHandle(World world) {
    try {
        return getMethod(world.getClass(), "getHandle").invoke(world);
    }
    catch (Exception ex) {
        FunnyGuilds.getInstance().getPluginLogger().error("Could not get world handle", ex);
        
        return null;
    }
}
 
Example #22
Source File: GameFile.java    From ZombieEscape with GNU General Public License v2.0 5 votes vote down vote up
public ArrayList<Location> getLocations(World world, String path) {
    ArrayList<Location> spawns = new ArrayList<>();
    world = world == null ? Bukkit.getWorld(path + ".World") : world;

    for (String set : config.getConfigurationSection(path).getKeys(false)) {
        if (!set.equals("Amount")) {
            spawns.add(locationFromConfig(world, path + "." + set + ".Location"));
        }
    }
    spawns.trimToSize(); // Trim any unnecessary array values
    return spawns;
}
 
Example #23
Source File: NetherStartListener.java    From UhcCore with GNU General Public License v3.0 5 votes vote down vote up
@EventHandler
public void onPreTeleport(UhcPreTeleportEvent e){
    GameManager gm = e.getGameManager();
    PlayersManager pm = gm.getPlayersManager();

    World nether = Bukkit.getWorld(gm.getConfiguration().getNetherUuid());
    double maxDistance = 0.9 * (nether.getWorldBorder().getSize()/2);

    for(UhcTeam team : pm.listUhcTeams()){
        Location newLoc = pm.findRandomSafeLocation(nether, maxDistance);
        Bukkit.broadcastMessage("Loc: " + newLoc.toString());
        team.setStartingLocation(newLoc);
    }
}
 
Example #24
Source File: Util.java    From SkyWarsReloaded with GNU General Public License v3.0 5 votes vote down vote up
public boolean isSpawnWorld(World world) {
	if (SkyWarsReloaded.getCfg().getSpawn() != null) {
		if (world.equals(SkyWarsReloaded.getCfg().getSpawn().getWorld())) {
			return true;
		}
	}
	return false;
}
 
Example #25
Source File: CraftMapView.java    From Thermos with GNU General Public License v3.0 5 votes vote down vote up
public World getWorld() {
    int dimension = worldMap.dimension; // Cauldron - byte -> int for Forge
    for (World world : Bukkit.getServer().getWorlds()) {
        if (((CraftWorld) world).getHandle().provider.dimensionId == dimension) {
            return world;
        }
    }
    return null;
}
 
Example #26
Source File: HorseModifier.java    From civcraft with GNU General Public License v2.0 5 votes vote down vote up
/**
* Spawns a horse at a given location
*/
public static HorseModifier spawn(Location loc) {
    World w = loc.getWorld();
    try {
        Object worldServer = ReflectionUtil.getMethod("getHandle", w.getClass(), 0).invoke(w);
        Object entityHorse = ReflectionUtil.getClass("EntityHorse", worldServer);
        ReflectionUtil.getMethod("setPosition", entityHorse.getClass(), 3).invoke(entityHorse, loc.getX(), loc.getY(), loc.getZ());
        ReflectionUtil.getMethod("addEntity", worldServer.getClass(), 1).invoke(worldServer, entityHorse);
        return new HorseModifier(entityHorse);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #27
Source File: GameFile.java    From ZombieEscape with GNU General Public License v2.0 5 votes vote down vote up
public ArrayList<Checkpoint> getCheckpoints(World world) {
    ArrayList<Checkpoint> checkpoints = new ArrayList<>();
    for (String key : config.getConfigurationSection("Checkpoints").getKeys(false)) {
        if (key.equals("Amount")) {
            continue; // Skip, this is just to keep track
        }

        Checkpoint checkpoint = new Checkpoint();
        checkpoint.setId(Integer.parseInt(key));
        checkpoint.setLocation(locationFromConfig(world, "Checkpoints." + key + ".Location"));
        checkpoints.add(checkpoint);
    }
    return checkpoints;
}
 
Example #28
Source File: GDClaimManager.java    From GriefDefender with MIT License 5 votes vote down vote up
public void createWildernessClaim(World world) {
    final Vector3i lesserCorner = new Vector3i(-30000000, 0, -30000000);
    final Vector3i greaterCorner = new Vector3i(29999999, 255, 29999999);
    // Use world UUID as wilderness claim ID
    GDClaim wilderness = new GDClaim(world, lesserCorner, greaterCorner, world.getUID(), ClaimTypes.WILDERNESS, null, false);
    wilderness.setOwnerUniqueId(GriefDefenderPlugin.WORLD_USER_UUID);
    wilderness.initializeClaimData(null);
    wilderness.claimData.save();
    wilderness.claimStorage.save();
    this.theWildernessClaim = wilderness;
    this.claimUniqueIdMap.put(wilderness.getUniqueId(), wilderness);
}
 
Example #29
Source File: SerializableLocation.java    From uSkyBlock with GNU General Public License v3.0 5 votes vote down vote up
public Location getLocation() {
    final World w = Bukkit.getWorld(world);
    if (w == null) {
        return null;
    }
    final Location toRet = new Location(w, x, y, z);
    return toRet;
}
 
Example #30
Source File: SentinelUtilities.java    From Sentinel with MIT License 5 votes vote down vote up
/**
 * Gets the entity for a given UUID.
 */
public static Entity getEntityForID(UUID id) {
    if (!SentinelVersionCompat.v1_12) {
        for (World world : Bukkit.getServer().getWorlds()) {
            for (Entity e : world.getEntities()) {
                if (e.getUniqueId().equals(id)) {
                    return e;
                }
            }
        }
        return null;
    }
    return Bukkit.getServer().getEntity(id);
}