Java Code Examples for org.bukkit.World

The following are top voted examples for showing how to use org.bukkit.World. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: AntiCheat   File: Calculations.java   Source Code and License 7 votes vote down vote up
public static boolean areAjacentBlocksBright(World world, int x, int y, int z, int countdown) {
    if(Orebfuscator.nms.getBlockLightLevel(world, x, y, z) > 0) {
        return true;
    }

    if (countdown == 0)
        return false;

    if (areAjacentBlocksBright(world, x, y + 1, z, countdown - 1))
        return true;
    if (areAjacentBlocksBright(world, x, y - 1, z, countdown - 1))
        return true;
    if (areAjacentBlocksBright(world, x + 1, y, z, countdown - 1))
        return true;
    if (areAjacentBlocksBright(world, x - 1, y, z, countdown - 1))
        return true;
    if (areAjacentBlocksBright(world, x, y, z + 1, countdown - 1))
        return true;
    if (areAjacentBlocksBright(world, x, y, z - 1, countdown - 1))
        return true;

    return false;
}
 
Example 2
Project: AntiCheat   File: BlockUpdate.java   Source Code and License 7 votes vote down vote up
private static void invalidateCachedChunks(World world, Set<ChunkCoord> invalidChunks) {
    if(invalidChunks.isEmpty() || !OrebfuscatorConfig.UseCache) return;

    File cacheFolder = new File(OrebfuscatorConfig.getCacheFolder(), world.getName());

    for(ChunkCoord chunk : invalidChunks) {
        ObfuscatedCachedChunk cache = new ObfuscatedCachedChunk(cacheFolder, chunk.x, chunk.z);
        cache.invalidate();

        //Orebfuscator.log("Chunk x = " + chunk.x + ", z = " + chunk.z + " is invalidated");/*debug*/
    }
}
 
Example 3
Project: UltimateSpawn   File: Warn.java   Source Code and License 6 votes vote down vote up
public static void runWarnSystemTask(MainClass plugin) {
	
	new BukkitRunnable() {

		public void run() {
			double ticks = Tps.getTPS();
			if (ticks <= 15.0D) {
				onPrevient();
			} else if (ticks <= 5.0D) {
				onCritique();
				Bukkit.getServer().savePlayers();
				for (World world : Bukkit.getWorlds()) {
		            world.save();
				}
			}
			
		}
		
	}.runTaskTimerAsynchronously(plugin, 40L, 60L);
	
}
 
Example 4
Project: CustomRecipes   File: SimpleShapelessRecipe.java   Source Code and License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean matches(CraftingInventory craftingInventory, World world) {
	final List<ChoiceIngredient> ingredients = new ArrayList<>(this.ingredients);
	final List<ItemStack> contents = Arrays.asList(craftingInventory.getMatrix())
			.stream().filter(i -> !InventoryUtils.isEmptyStack(i))
			.collect(Collectors.toList());
	
	for (ItemStack stack : contents) {
		boolean match = false;
		for (int ingredientIndex = 0; ingredientIndex < ingredients.size(); ingredientIndex++) {
			ChoiceIngredient ingredient = ingredients.get(ingredientIndex);
			if (ingredient.isIngredient(stack)) {
				ingredients.remove(ingredientIndex);
				match = true;
				break;
			}
		}
		
		//there was no matching ingredient for the current ItemStack
		if (!match) return false;
	}
	
	//return true if there are no unused ingredients left over
	return ingredients.isEmpty();
}
 
Example 5
Project: uppercore   File: ParticlePacket.java   Source Code and License 6 votes vote down vote up
private void forEveryoneAround(Location center, double radius, Consumer<Player> action) {
    int chunkRadius = (int) Math.ceil(radius) >> 4;
    double squared = radius * radius;
    final int x = center.getBlockX() >> 4;
    final int z = center.getBlockZ() >> 4;

    int ix = x - chunkRadius;
    int ex = x + chunkRadius;

    int iz = z - chunkRadius;
    int ez = z + chunkRadius;

    final World world = center.getWorld();
    for (int chX = ix; chX <= ex; chX++) {
        for (int chZ = iz; chZ <= ez; chZ++) {
            if(world.isChunkLoaded(chX, chZ)) {
                for (Entity e : world.getChunkAt(chX, chZ).getEntities()) {
                    if (e instanceof Player && e.getLocation().distanceSquared(center) <= squared) {
                        action.accept((Player) e);
                    }
                }
            }
        }
    }
}
 
Example 6
Project: ClaimChunk   File: ChunkHelper.java   Source Code and License 6 votes vote down vote up
public static boolean canEdit(World world, int x, int z, UUID player) {
       if (Bukkit.getPlayer(player).hasPermission("claimchunk.admin"))
           return true;
       ChunkHandler ch = ClaimChunk.getInstance().getChunkHandler();
	PlayerHandler ph = ClaimChunk.getInstance().getPlayerHandler();
	if (!ch.isClaimed(world, x, z)) {
		return true;
	}
	if (ch.isOwner(world, x, z, player)) {
		return true;
	}
	if (ph.hasAccess(ch.getOwner(world, x, z), player)) {
		return true;
	}
	return false;
}
 
Example 7
Project: Scorch   File: RegionMapGen.java   Source Code and License 6 votes vote down vote up
public static void genRegionMap(World world) {
    double sizexz = world.getWorldBorder().getSize();
    map = new String[(int)sizexz][(int)sizexz];
    System.out.println("Generating 2d world map, worldborder size: " + sizexz);
    for (double x=0; x < sizexz; x++) {
        for (double z=0; z < sizexz; z++) {
            Block currentBlock = world.getBlockAt(new Location(world, x,lavalevel,z));

            if (currentBlock.getType().equals(Material.LAVA) ||  currentBlock.getType().equals(Material.STATIONARY_LAVA)) {
                // lava block
                map[(int)x][(int)z] = "lava";
            } else {
                // non lava block
                map[(int)x][(int)z] = "unknown";
            }

        }
    }


    System.out.println("Finished generating 2d world map: " + map.toString());
}
 
Example 8
Project: SurvivalAPI   File: SurvivalGameLoop.java   Source Code and License 6 votes vote down vote up
/**
 * Close the nether, teleport players to OverWorld
 */
public void closeNether()
{
    this.netherClosed = true;
    World nether = this.plugin.getServer().getWorld("world_nether");
    World overworld = this.plugin.getServer().getWorld("world");
    if (nether == null)
        return ;
    this.plugin.getServer().getOnlinePlayers().forEach(player ->
    {
        Location location = player.getLocation();
        if (location.getWorld().equals(nether))
        {
            Location newLocation = new Location(overworld, location.getX() * 8, 0, location.getZ());
            newLocation.setY(newLocation.getWorld().getHighestBlockYAt(newLocation));
            player.teleport(newLocation);
            player.sendMessage(ChatColor.RED + "Le nether a été fermé, vous avez été téléporté dans le monde normal.");
        }
    });
}
 
Example 9
Project: AddGun   File: StandardGun.java   Source Code and License 6 votes vote down vote up
/**
 * Override this class, you can use it to provide particle effects along travel path. 
 * 
 * It is called after all other handling is done. Keep it lightweight
 * 
 * @param start The start location of flight
 * @param end The end location of impact / miss
 * @param type the type of bullet in play
 * @param endOfFlight is the bullet still flying after this or has it impacted?
 */
public void flightPath(Location start, Location end, Bullet type, boolean endOfFlight) {
	// no special flight path stuff. maybe a whizzing sound?

	World world = start.getWorld();
	if (endOfFlight) {
		// make a new sound where it hits.
		world.playSound(end, Sound.ENTITY_FIREWORK_BLAST, 1.0f, 1.5f);
	}
	if (type.getFireChance() > 0.0d) {
		if (start != null) {
			double distance = end.distance(start);

			Vector vector = end.subtract(start).toVector();
			vector = vector.multiply(0.1d / distance);
			for (int i = 0; i < distance; i++) {
				world.spawnParticle(Particle.SMOKE_NORMAL, start.add(vector), 5, 0.01, 0.01, 0.01, 0.001);
			}
		}
	}
}
 
Example 10
Project: libtrails   File: Particle.java   Source Code and License 6 votes vote down vote up
private void spawn0(Object o, Location loc, int tick) {
    float offx = ((Number) (this.offx instanceof Function ?
            ((Function)this.offx).apply(tick) : this.offx)).floatValue();

    float offy = ((Number) (this.offy instanceof Function ?
            ((Function)this.offy).apply(tick) : this.offy)).floatValue();

    float offz = ((Number) (this.offz instanceof Function ?
            ((Function)this.offz).apply(tick) : this.offz)).floatValue();

    float speed = ((Number) (this.speed instanceof Function ?
            ((Function)this.speed).apply(tick) : this.speed)).floatValue();

    int n = ((Number) (this.particleCount instanceof Function ?
            ((Function)this.particleCount).apply(tick) :
            this.particleCount)).intValue();

    if (o instanceof Player) {
        ((Player)o).spigot().playEffect(loc, effect, id, data,
                offx, offy, offz, speed, n, radius);
    } else {
        ((World)o).spigot().playEffect(loc, effect, id, data,
                offx, offy, offz, speed, n, radius);
    }
}
 
Example 11
Project: DragonEggDrop   File: RespawnListeners.java   Source Code and License 6 votes vote down vote up
@EventHandler
public void onPlayerSwitchWorlds(PlayerChangedWorldEvent event) {
	World world = event.getPlayer().getWorld();
	if (world.getEnvironment() != Environment.THE_END) return;
	
	EndWorldWrapper worldWrapper = manager.getWorldWrapper(world);
	
	// Start the respawn countdown if joining an empty world
	if (plugin.getConfig().getBoolean("respawn-on-join", false)) {
		if (world.getPlayers().size() > 1 || worldWrapper.isRespawnInProgress()
				|| world.getEntitiesByClass(EnderDragon.class).size() == 0) 
			return;
		
		manager.getWorldWrapper(world).startRespawn(RespawnType.JOIN);
	}
	
	// Reset end crystal states just in case something went awry
	if (!worldWrapper.isRespawnInProgress()) {
		world.getEntitiesByClass(EnderCrystal.class).forEach(e -> {
			e.setInvulnerable(false);
			e.setBeamTarget(null);
		});
	}
}
 
Example 12
Project: PA   File: Dagas.java   Source Code and License 6 votes vote down vote up
public void play(TOAUser u){
    if (!canUse(u)) return;
    if (isInCooldown(u, getName())) return;
    int lvl = u.getUserData().getLvl();

    for (int x = 0; x < r.nextInt(4) + 2; x++) {
        final Item d1 = u.getLoc().getWorld().dropItemNaturally(u.getLoc(), new ItemStack(Material.IRON_SWORD));

        d1.setVelocity(u.getPlayer().getVelocity().multiply(2));

        plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
            World w = d1.getLocation().getWorld();

            w.getNearbyEntities(d1.getLocation(), 1, 1, 1).stream()
                    .filter(en -> !en.getType().equals(EntityType.PLAYER)).forEach(en -> {
                if (en instanceof Monster) ((Monster) en).damage(40 + (lvl * 0.7));
                d1.remove();
            });
        }, 0, 20);
    }
    cool.setOnCooldown(getName());
}
 
Example 13
Project: SkyWarsReloaded   File: NMSHandler.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void updateChunks(World world, List<Chunk> chunks) {
	for (Chunk currentChunk: chunks) {
		net.minecraft.server.v1_7_R4.World mcWorld = ((CraftChunk) currentChunk).getHandle().world;
        for (EntityPlayer ep : (List<EntityPlayer>) mcWorld.players) {
                ep.chunkCoordIntPairQueue.add(new ChunkCoordIntPair(currentChunk.getX(), currentChunk.getZ()));
        }
	}
}
 
Example 14
Project: bskyblock   File: ChunkGeneratorWorld.java   Source Code and License 5 votes vote down vote up
@Override
public ChunkData generateChunkData(World world, Random random, int chunkX, int chunkZ, ChunkGenerator.BiomeGrid biomeGrid) {
    if (world.getEnvironment().equals(World.Environment.NETHER)) {
        return generateNetherChunks(world, random, chunkX, chunkZ, biomeGrid);
    }
    ChunkData result = createChunkData(world);
    if (Settings.seaHeight != 0) {
        for (int x = 0; x < 16; x++) {
            for (int z = 0; z < 16; z++) {
                for (int y = 0; y < Settings.seaHeight; y++) {
                    result.setBlock(x, y, z, Material.STATIONARY_WATER);
                }
            }
        }

    }
    return result;
}
 
Example 15
Project: ProjectAres   File: LobbyConfig.java   Source Code and License 5 votes vote down vote up
private Vector getVector(World world, String key, Vector def) {
    try {
        Vector v = ConfigUtils.getVector(config, key, null);
        if(v != null) return v;

        String rule = world.getGameRuleValue(key);
        if(!"".equals(rule)) {
            return Vectors.parseVector(rule);
        }

        return def;
    } catch(RuntimeException ex) {
        logger.log(Level.SEVERE, "Error parsing vector '" + key + "' from lobby config: " + ex.getMessage(), ex);
        throw ex;
    }
}
 
Example 16
Project: DungeonGen   File: BlockSpawnTask.java   Source Code and License 5 votes vote down vote up
@Override
public void run() {
	World world = parent.getPlugin().world;

	Helper.fillVolume(world, parent.toGlobal(targetRegion.getPos1()),
			                 parent.toGlobal(targetRegion.getPos2()), blockMaterial);
	try {
		targetRegion.shift(incrementVec);
	} catch (RegionOperationException e) {
		parent.getPlugin().getLogger().info("Shifting target region for room task failded!");
		e.printStackTrace();
	}
}
 
Example 17
Project: NavyCraft2-Lite   File: Craft.java   Source Code and License 5 votes vote down vote up
public static void telegraphDingThread(final Player player) {
	new Thread() {

		@Override
		public void run() {

			setPriority(Thread.MIN_PRIORITY);

			// taskNum = -1;
			try {
				World cw = player.getWorld();
				Location loc = player.getLocation();
				for (int i = 0; i < 2; i++) {
					sleep(200);
					cw.playSound(loc, Sound.BLOCK_ANVIL_PLACE, 1.0f, 1.9f);

				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}.start(); // , 20L);
}
 
Example 18
Project: ProjectAres   File: PlayerListener.java   Source Code and License 5 votes vote down vote up
private double spawnRadius(World world) {
    try {
        return spawnRadius = config.getSpawnRadius(world);
    } catch(Throwable e) {
        lobby.getLogger().log(Level.SEVERE, "Failed to get spawn radius, using last good value", e);
        return spawnRadius;
    }
}
 
Example 19
Project: HCFCore   File: RoadFaction.java   Source Code and License 5 votes vote down vote up
public SouthRoadFaction() {
    super("SouthRoad");
    for (World world : Bukkit.getWorlds()) {
        World.Environment environment = world.getEnvironment();
        if (environment != World.Environment.THE_END) {
            int roadLength = SettingsYML.ROAD_LENGTHS.get(environment);
            int offset = SettingsYML.SPAWN_RADIUS_MAP.get(environment) + 1;
            addClaim(new Claim(this, new Location(world, ROAD_WIDTH_LEFT, ROAD_MIN_HEIGHT, offset), new Location(world, -ROAD_WIDTH_RIGHT, ROAD_MAX_HEIGHT, roadLength - ROAD_EDGE_DIFF)), null);
        }
    }
}
 
Example 20
Project: EscapeLag   File: AntiBedExplode.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void CheckInterackBed(PlayerInteractEvent e) {
    if (ConfigPatch.noBedExplore == true) {
        Player p = e.getPlayer();
        Block block = e.getClickedBlock();
        if (e.getAction() == Action.RIGHT_CLICK_BLOCK) {
            if (block.getType() == Material.BED_BLOCK) {
                if (p.getWorld().getEnvironment() == World.Environment.NETHER || p.getWorld().getEnvironment() == World.Environment.THE_END) {
                    e.setCancelled(true);
                    AzureAPI.log(p, ConfigPatch.AntiBedExplodeTipMessage);
                }
            }
        }
    }
}
 
Example 21
Project: ProjectAres   File: NMSHacks.java   Source Code and License 5 votes vote down vote up
public static void playBlockPlaceSound(World bukkitWorld, Vector pos, Material material, float volume) {
    if (!material.isBlock()) {
        return;
    }
    playCustomSound(bukkitWorld,
                    pos.toLocation(bukkitWorld),
                    CraftMagicNumbers.getBlock(material).getStepSound().placeSound(),
                    SoundCategory.BLOCKS,
                    volume,
                    1f);
}
 
Example 22
Project: Sunscreen   File: PluginSettings.java   Source Code and License 5 votes vote down vote up
/**
 * Returns if the world is disabled.
 * 
 * @param world
 *            The target worlds.
 * @return True if the world is disabled.
 * @author HomieDion
 * @since 1.1.0
 */
public boolean isDisabledWorld(final World world) {
	for (final String name : worlds) {
		if (world.getName().equalsIgnoreCase(name)) {
			return true;
		}
	}

	// Not disabled
	return false;
}
 
Example 23
Project: ProjectAres   File: FiniteBlockRegion.java   Source Code and License 5 votes vote down vote up
public FiniteBlockRegion fromWorld(Region region, World world, Predicate<Block> filter) {
    if(region instanceof CuboidRegion && mapProto.isOlderThan(REGION_FIX_VERSION)) {
        // Due to an old bug, legacy maps have cuboids that are one block too big
        region = new CuboidRegion(region.getBounds().minimum(), region.getBounds().maximum().plus(1, 1, 1));
    }

    return new FiniteBlockRegion(region.blockPositions()
                                       .filter(pos -> filter.test(world.getBlockAt(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ())))
                                       .collect(Collectors.toCollection(BlockVectorSet::new)));
}
 
Example 24
Project: NavyCraft2-Lite   File: TeleportFix_1_11.java   Source Code and License 5 votes vote down vote up
public static void updateEntity(Entity entity, List<Player> observers) {

	World world = entity.getWorld();
	WorldServer worldServer = ((CraftWorld) world).getHandle();

	EntityTracker tracker = worldServer.tracker;
	EntityTrackerEntry entry = (EntityTrackerEntry) tracker.trackedEntities
			.get(entity.getEntityId());

	List<EntityHuman> nmsPlayers = getNmsPlayers(observers);

	// Force Minecraft to resend packets to the affected clients
	entry.trackedPlayers.removeAll(nmsPlayers);
	entry.scanPlayers(nmsPlayers);
}
 
Example 25
Project: ZentrelaCore   File: RSerializer.java   Source Code and License 5 votes vote down vote up
public static Location deserializeLocation(String s) {
    Location def = SakiCore.plugin.getServer().getWorlds().get(0).getSpawnLocation();
    if (s.length() == 0)
        return def;
    String[] data = s.split(Pattern.quote(LOCATION_DIVIDER));
    if (data.length == 0)
        return def;
    try {
        double x = Double.parseDouble(data[0]);
        double y = Double.parseDouble(data[1]);
        if (y < 1)
            y = 1;
        double z = Double.parseDouble(data[2]);
        float yaw = Float.parseFloat(data[3]);
        float pitch = Float.parseFloat(data[4]);
        World w = SakiCore.plugin.getServer().getWorld(data[5]);
        if (w == null) {
            SakiCore.plugin.getServer().getWorlds().get(0).getSpawnLocation();
        }
        return new Location(w, x, y, z, yaw, pitch);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Corrupted location save: " + s);
    }
    return def;
}
 
Example 26
Project: EscapeLag   File: AutoSave.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void JoinTaskGiver(PlayerJoinEvent e) {
    if (ConfigOptimize.AutoSaveenable == false) {
        return;
    }
    final Player p = e.getPlayer();
    TaskId.put(p, Bukkit.getScheduler().scheduleSyncRepeatingTask(EscapeLag.MainThis, new Runnable() {

        @Override
        public void run() {
            Chunk chunk = p.getLocation().getChunk();
            Chunk LastChunk = PlayerInChunkMap.get(p);
            if (LastChunk != chunk) {
                if (LastChunk == null) {
                    PlayerInChunkMap.put(p, chunk);
                    return;
                }
                if (PlayerClickedMap.containsValue(LastChunk)) {
                    return;
                }
                World world = LastChunk.getWorld();
                if (LastChunk.isLoaded() == true) {
                	world.unloadChunk(LastChunk.getX(), LastChunk.getZ(), true);
                    LastChunk.load();
                } else {
                    LastChunk.load();
                    world.unloadChunk(LastChunk.getX(), LastChunk.getZ(), true);
                }
            }
            PlayerInChunkMap.put(p, chunk);
            p.saveData();
        }
    }, ConfigOptimize.AutoSaveInterval * 20, ConfigOptimize.AutoSaveInterval * 20));
}
 
Example 27
Project: AntiCheat   File: BlockUpdate.java   Source Code and License 5 votes vote down vote up
public static void Update(List<Block> blocks) {
    if (blocks.isEmpty()) {
        return;
    }

    World world = blocks.get(0).getWorld();
    HashSet<IBlockInfo> updateBlocks = new HashSet<IBlockInfo>();
    HashSet<ChunkCoord> invalidChunks = new HashSet<ChunkCoord>();

    for (Block block : blocks) {
        if (needsUpdate(block)) {
            IBlockInfo blockInfo = Orebfuscator.nms.getBlockInfo(world, block.getX(), block.getY(), block.getZ());

            GetAjacentBlocks(updateBlocks, world, blockInfo, OrebfuscatorConfig.UpdateRadius);

            if((blockInfo.getX() & 0xf) == 0) {
                invalidChunks.add(new ChunkCoord((blockInfo.getX() >> 4) - 1, blockInfo.getZ() >> 4));
            } else if(((blockInfo.getX() + 1) & 0xf) == 0) {
                invalidChunks.add(new ChunkCoord((blockInfo.getX() >> 4) + 1, blockInfo.getZ() >> 4));
            } else if(((blockInfo.getZ()) & 0xf) == 0) {
                invalidChunks.add(new ChunkCoord(blockInfo.getX() >> 4, (blockInfo.getZ() >> 4) - 1));
            } else if(((blockInfo.getZ() + 1) & 0xf) == 0) {
                invalidChunks.add(new ChunkCoord(blockInfo.getX() >> 4, (blockInfo.getZ() >> 4) + 1));
            }
        }
    }

    sendUpdates(world, updateBlocks);

    invalidateCachedChunks(world, invalidChunks);
}
 
Example 28
Project: DragonEggDrop   File: DragonLifeListeners.java   Source Code and License 5 votes vote down vote up
@EventHandler
public void onDragonDeath(EntityDeathEvent event) {
	if (!(event.getEntity() instanceof EnderDragon)) return;
	
	EnderDragon dragon = (EnderDragon) event.getEntity();
	DragonBattle dragonBattle = plugin.getNMSAbstract().getEnderDragonBattleFromDragon(dragon);
	
	World world = event.getEntity().getWorld();
	EndWorldWrapper worldWrapper = plugin.getDEDManager().getWorldWrapper(world);
	
	BattleStateChangeEvent bscEventCrystals = new BattleStateChangeEvent(dragonBattle, dragon, BattleState.BATTLE_COMMENCED, BattleState.BATTLE_END);
	Bukkit.getPluginManager().callEvent(bscEventCrystals);

	new BukkitRunnable() {
		@Override
		public void run() {
			if (plugin.getNMSAbstract().getEnderDragonDeathAnimationTime(dragon) >= 185) { // Dragon is dead at 200
				new DragonDeathRunnable(plugin, worldWrapper, dragon);
				this.cancel();
			}
		}
	}.runTaskTimer(plugin, 0L, 1L);
}
 
Example 29
Project: VoxelGamesLibv2   File: NMSUtil.java   Source Code and License 5 votes vote down vote up
public static void flushSaveQueue(@Nonnull World world) {
    try {
        if (nmsWorldServer == null) {
            nmsWorldServer = getNmsClass("WorldServer");
        }
        if (worldGetHandle == null) {
            worldGetHandle = world.getClass().getMethod("getHandle");
        }
        if (worldServerFlushSave == null) {
            worldServerFlushSave = nmsWorldServer.getMethod("flushSave");
        }

        Object worldServer = worldGetHandle.invoke(world);
        worldServerFlushSave.invoke(worldServer);
    } catch (Exception ex) {
        log.warning("Error while trying to flush the save queue!");
        ex.printStackTrace();
    }
}
 
Example 30
Project: Warzone   File: SimpleOwnedMobTracker.java   Source Code and License 5 votes vote down vote up
public void clear(@Nonnull World world) {
    Preconditions.checkNotNull(world, "world");

    // clear information about owned mobs in that world
    for (Entry<LivingEntity, Player> livingEntityPlayerEntry : this.ownedMobs.entrySet()) {
        LivingEntity entity = livingEntityPlayerEntry.getKey();
        if (entity.getWorld().equals(world)) {
            entity.remove();
        }
    }
}
 
Example 31
Project: WC   File: WeatherCMD.java   Source Code and License 5 votes vote down vote up
@Override
public void run (WCUser user, String lbl, String[] args) {
    World mundo = user.getPlayer().getWorld();
    int parametrosdelluvia = (300 + (new Random()).nextInt(600)) * 20;

    switch(args[0].toLowerCase()) {
        case "sun":
        case "sol":
        case "clear":
            //sol
            mundo.setWeatherDuration(0);
            mundo.setStorm(false);
            mundo.setThundering(false);
            mundo.setThunderDuration(0);
            break;
        case "rain":
        case "lluvia":
            //luvia
            mundo.setWeatherDuration(parametrosdelluvia);
            mundo.setStorm(true);
            mundo.setThundering(false);
            break;
        case "thunder":
        case "tormenta":
            //tormenta
            mundo.setWeatherDuration(parametrosdelluvia);
            mundo.setThunderDuration(parametrosdelluvia);
            mundo.setStorm(true);
            mundo.setThundering(true);
            break;
        default:
            break;
    }
    user.sendMessagePrefix("Tiempo &2" + args[0].toLowerCase());
}
 
Example 32
Project: HCFCore   File: Claim.java   Source Code and License 5 votes vote down vote up
public Claim(Faction faction, World world, int x1, int y1, int z1, int x2, int y2, int z2)
{
  super(world, x1, y1, z1, x2, y2, z2);
  this.name = generateName();
  this.factionUUID = faction.getUniqueID();
  this.claimUniqueID = UUID.randomUUID();
}
 
Example 33
Project: DragonEggDrop   File: EndWorldWrapper.java   Source Code and License 5 votes vote down vote up
/**
 * Construct a new EndWorldWrapper around an existing world
 * 
 * @param plugin the plugin instance
 * @param world the world to wrap
 */
protected EndWorldWrapper(DragonEggDrop plugin, World world) {
	this.plugin = plugin;
	this.world = world.getUID();
	
	if (world.getEnvironment() != Environment.THE_END)
		throw new IllegalArgumentException("EndWorldWrapper worlds must be of environment \"THE_END\"");
}
 
Example 34
Project: Transport-Pipes   File: PipeAPI.java   Source Code and License 5 votes vote down vote up
/**
 * Destroys all ducts in this world.
 */
public static void destroyDucts(World world) {
	List<Duct> toDestroy = new ArrayList<>();

	Map<BlockLoc, Duct> ductMap = TransportPipes.instance.getDuctMap(world);
	if (ductMap != null) {
		synchronized (ductMap) {
			toDestroy.addAll(ductMap.values());
		}
	}

	for (Duct duct : toDestroy) {
		destroyDuct(duct.getBlockLoc());
	}
}
 
Example 35
Project: HCFCore   File: CoreListener.java   Source Code and License 5 votes vote down vote up
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH)
public void onBlockPlace(BlockPlaceEvent event) {
    Player player = event.getPlayer();
    if (player.getWorld().getEnvironment() == World.Environment.NETHER && event.getBlock().getState() instanceof CreatureSpawner
            && !player.hasPermission(ProtectionListener.PROTECTION_BYPASS_PERMISSION)) {

        event.setCancelled(true);
        player.sendMessage(ChatColor.RED + "You may not place spawners in the nether.");
    }
}
 
Example 36
Project: SurvivalAPI   File: SurvivalPlugin.java   Source Code and License 5 votes vote down vote up
/**
 * Called when the world's loading process is finished
 *
 * @param world World
 * @param time Loading time
 */
public void finishGeneration(World world, long time)
{
    this.getLogger().info("Ready in " + time + "ms");
    this.getServer().setSpawnRadius(0);
    this.api.fireEvents(SurvivalAPI.EventType.AFTERGENERATION);
}
 
Example 37
Project: NeverLag   File: AntiDoubleLogin.java   Source Code and License 5 votes vote down vote up
private boolean checkOnline(String username) {
	try {
		for (World w : Bukkit.getWorlds()) {
			for (Player p : w.getPlayers()) {
				if (p != null && p.getName().equalsIgnoreCase(username)) {
					return true;
				}
			}
		}
	} catch (Exception ignore) {
		// 忽略
	}
	return false;
}
 
Example 38
Project: SuperiorCraft   File: NMSAdapter.java   Source Code and License 5 votes vote down vote up
public static Object getWorld(World world) {
	try {
		Object bs = getClass("WorldServer").getDeclaredMethod("getHandle").invoke(world);
		return bs;
	} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
			| SecurityException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return null;
}
 
Example 39
Project: HCFCore   File: FactionStuckArgument.java   Source Code and License 5 votes vote down vote up
public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
    if(!(sender instanceof Player)) {
        sender.sendMessage(ChatColor.RED + "This command is only executable by players.");
        return true;
    }
    final Player player = (Player) sender;
    if(player.getWorld().getEnvironment() != World.Environment.NORMAL) {
        sender.sendMessage(ChatColor.RED + "You can only use this command from the overworld.");
        return true;
    }
    if(plugin.getFactionManager().getFactionAt(((Player) sender).getLocation()) instanceof SpawnFaction){
        sender.sendMessage(ChatColor.RED + "You cannot " + label + " " + this.getName() + " inside of Spawn");
        return true;
    }
    final StuckTimer stuckTimer = this.plugin.getTimerManager().getStuckTimer();
    if(!stuckTimer.setCooldown(player, player.getUniqueId())) {
        sender.sendMessage(ChatColor.YELLOW + "Your " + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has a remaining " + ChatColor.LIGHT_PURPLE + DurationFormatUtils.formatDurationWords(stuckTimer.getRemaining(player), true, true)+ChatColor.YELLOW + '.');
        return true;
    }
    sender.sendMessage(ChatColor.YELLOW + stuckTimer.getDisplayName() + ChatColor.YELLOW + " timer has started. " + "\nTeleportation will commence in " + ChatColor.LIGHT_PURPLE + DurationFormatter.getRemaining(stuckTimer.getRemaining(player), true, false) + ChatColor.YELLOW + ". " + "\nThis will cancel if you move more than " + 5 + " blocks.");
    return true;
}
 
Example 40
Project: Uranium   File: CraftServer.java   Source Code and License 5 votes vote down vote up
@Override
public boolean unloadWorld(World world, boolean save) {
    if (world == null) {
        return false;
    }

    net.minecraft.world.WorldServer handle = ((CraftWorld) world).getHandle();

    if (!(console.worlds.contains(handle))) {
        return false;
    }

    if (handle.playerEntities.size() > 0) {
        return false;
    }

    WorldUnloadEvent e = new WorldUnloadEvent(handle.getWorld());
    pluginManager.callEvent(e);

    if (e.isCancelled()) {
        return false;
    }

    if (save) {
        try {
            handle.saveAllChunks(true, null);
            handle.flush();
            WorldSaveEvent event = new WorldSaveEvent(handle.getWorld());
            getPluginManager().callEvent(event);
        } catch (net.minecraft.world.MinecraftException ex) {
            getLogger().log(Level.SEVERE, null, ex);
            FMLLog.log(org.apache.logging.log4j.Level.ERROR, ex, "Failed to save world " + handle.getWorld().getName() + " while unloading it.");
        }
    }
    MinecraftForge.EVENT_BUS.post(new WorldEvent.Unload(handle)); // Cauldron - fire unload event before removing world
    worlds.remove(world.getName().toLowerCase());
    DimensionManager.setWorld(handle.provider.dimensionId, null); // Cauldron - remove world from DimensionManager
    return true;
}