类org.bukkit.World源码实例Demo

下面列出了怎么用org.bukkit.World的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: PGM   文件: MatchImpl.java
@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);
  }
}
 
源代码2 项目: Item-NBT-API   文件: TilesCustomNBTInjectorTest.java
@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);
		}
	}
}
 
源代码3 项目: SkyWarsReloaded   文件: SignListener.java
@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);
        } 
   }
}
 
源代码4 项目: Shopkeepers   文件: CitizensShop.java
@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);
}
 
源代码5 项目: civcraft   文件: ArenaManager.java
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;
}
 
源代码6 项目: Kettle   文件: CustomTimingsHandler.java
/**
 * 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);
}
 
源代码7 项目: AnnihilationPro   文件: GameMap.java
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();
//		}
	}
 
源代码8 项目: Harbor   文件: HarborCommand.java
@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;
}
 
源代码9 项目: Skript   文件: EvtAtTime.java
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();
}
 
源代码10 项目: PerWorldInventory   文件: LocationSerializer.java
/**
 * 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);
}
 
源代码11 项目: Skript   文件: EffPvP.java
@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;
}
 
源代码12 项目: GlobalWarming   文件: WorldConfig.java
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;
}
 
源代码13 项目: uSkyBlock   文件: WorldManager.java
/**
 * 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());
}
 
源代码14 项目: HubBasics   文件: Holograms.java
/**
 * 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);
}
 
源代码15 项目: SkyWarsReloaded   文件: MobSpawnEvent.java
@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);
		}
	}
}
 
源代码16 项目: FunnyGuilds   文件: Reflections.java
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;
    }
}
 
源代码17 项目: ZombieEscape   文件: GameFile.java
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;
}
 
源代码18 项目: SkyWarsReloaded   文件: Util.java
public boolean isSpawnWorld(World world) {
	if (SkyWarsReloaded.getCfg().getSpawn() != null) {
		if (world.equals(SkyWarsReloaded.getCfg().getSpawn().getWorld())) {
			return true;
		}
	}
	return false;
}
 
源代码19 项目: civcraft   文件: HorseModifier.java
/**
* 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;
    }
}
 
源代码20 项目: GriefDefender   文件: GDClaimManager.java
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);
}
 
源代码21 项目: Sentinel   文件: SentinelUtilities.java
/**
 * 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);
}
 
源代码22 项目: uSkyBlock   文件: SerializableLocation.java
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;
}
 
源代码23 项目: ZombieEscape   文件: GameFile.java
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;
}
 
源代码24 项目: Thermos   文件: CraftMapView.java
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;
}
 
源代码25 项目: UhcCore   文件: NetherStartListener.java
@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);
    }
}
 
源代码26 项目: UHC   文件: DifficultyModule.java
@Override
public void onEnable() {
    for (final World world : Bukkit.getWorlds()) {
        if (worlds.worldMatches(world)) {
            world.setDifficulty(Difficulty.HARD);
        }
    }
}
 
源代码27 项目: Skript   文件: ExprLocationAt.java
@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;
}
 
源代码28 项目: ce   文件: Bombardment.java
@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);
	}
}
 
源代码29 项目: SkyWarsReloaded   文件: NMSHandler.java
@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);
}
 
源代码30 项目: Skript   文件: WorldGuard6Hook.java
@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;
}
 
 类所在包
 同包方法