下面列出了怎么用org.bukkit.World的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
}
@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);
}
}
}
@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);
}
}
}
@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);
}
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;
}
/**
* 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);
}
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();
// }
}
@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;
}
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();
}
/**
* 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);
}
@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;
}
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;
}
/**
* 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());
}
/**
* 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);
}
@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);
}
}
}
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;
}
}
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;
}
public boolean isSpawnWorld(World world) {
if (SkyWarsReloaded.getCfg().getSpawn() != null) {
if (world.equals(SkyWarsReloaded.getCfg().getSpawn().getWorld())) {
return true;
}
}
return false;
}
/**
* 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;
}
}
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);
}
/**
* 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);
}
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;
}
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;
}
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;
}
@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);
}
}
@Override
public void onEnable() {
for (final World world : Bukkit.getWorlds()) {
if (worlds.worldMatches(world)) {
world.setDifficulty(Difficulty.HARD);
}
}
}
@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;
}
@SuppressWarnings("deprecation")
@Override
public void effect(Event e, ItemStack item, final int level) {
if(e instanceof EntityDamageByEntityEvent) {
EntityDamageByEntityEvent event = (EntityDamageByEntityEvent) e;
Entity target = event.getEntity();
final World world = target.getWorld();
Vector vec = new Vector(0, -5, 0);
Location spawnLocation = new Location(world, target.getLocation().getX(), 255, target.getLocation().getZ());
final FallingBlock b = world.spawnFallingBlock(spawnLocation, 46, (byte) 0x0);
b.setVelocity(vec);
new BukkitRunnable() {
Location l = b.getLocation();
@Override
public void run() {
l = b.getLocation();
if(b.isDead()) {
l.getBlock().setType(Material.AIR);
for(int i = 0; i <= TNTAmount + level; i++) {
TNTPrimed tnt = world.spawn(l, TNTPrimed.class);
tnt.setFuseTicks(0);
if(!Main.createExplosions)
tnt.setMetadata("ce.explosive", new FixedMetadataValue(getPlugin(), null));
}
this.cancel();
}
EffectManager.playSound(l, "ENTITY_ENDERDRAGON_GROWL", Volume, 2f);
}
}.runTaskTimer(getPlugin(), 0l, 5l);
}
}
@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);
}
@Override
@Nullable
public Region getRegion_i(final World world, final String name) {
final ProtectedRegion r = plugin.getRegionManager(world).getRegion(name);
if (r != null)
return new WorldGuardRegion(world, r);
return null;
}