org.bukkit.util.NumberConversions Java Examples

The following examples show how to use org.bukkit.util.NumberConversions. 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: CronusUtils.java    From TabooLib with MIT License 6 votes vote down vote up
public static long toMillis(String in) {
    long time = 0;
    StringBuilder current = new StringBuilder();
    for (String charAt : in.toLowerCase().split("")) {
        if (isInt(charAt)) {
            current.append(charAt);
        } else {
            switch (charAt) {
                case "d":
                    time += NumberConversions.toInt(current.toString()) * 24L * 60L * 60L * 1000L;
                    break;
                case "h":
                    time += NumberConversions.toInt(current.toString()) * 60L * 60L * 1000L;
                    break;
                case "m":
                    time += NumberConversions.toInt(current.toString()) * 60L * 1000L;
                    break;
                case "s":
                    time += NumberConversions.toInt(current.toString()) * 1000L;
                    break;
            }
            current = new StringBuilder();
        }
    }
    return time;
}
 
Example #2
Source File: CronusParser.java    From TabooLib with MIT License 6 votes vote down vote up
public static Location toLocation(Object in) {
    String str = String.valueOf(in);
    // 区域
    // world:0,80,0~0,90,0
    if (str.contains(":") && str.contains("~")) {
        String[] area = str.split("~");
        try {
            return new Location(Location.Mode.AREA, new org.bukkit.Location[] {toBukkitLocation(area[0].replace(":", ",")), toBukkitLocation(area[0].split(":")[0] + "," + area[1])}, null);
        } catch (Throwable ignored) {
            return new Location(Location.Mode.AREA, null, null);
        }
    }
    // 范围
    // world:0,80,0 r:10
    else if (str.contains("r:")) {
        String[] range = str.split("r:");
        return new Location(Location.Mode.RANGE, new org.bukkit.Location[] {toBukkitLocation(range[0].replace(":", ","))}, NumberConversions.toInt(range[1]));
    }
    // 单项
    // world,0,80,0;world,0,90,0
    else {
        return new Location(Location.Mode.POINT, null, Arrays.stream(str.split(";")).map(CronusParser::toBukkitLocation).toArray(org.bukkit.Location[]::new));
    }
}
 
Example #3
Source File: BukkitVariables.java    From ScoreboardStats with MIT License 6 votes vote down vote up
@Override
public void register() {
    register("health").scoreSupply(player -> NumberConversions.round(player.getHealth()));
    register("lifetime").scoreSupply(player -> player.getTicksLived() / (20 * MINUTE_TO_SECOND));
    register("no_damage_ticks").scoreSupply(player -> player.getNoDamageTicks() / (20 * MINUTE_TO_SECOND));
    register("last_damage").scoreSupply(player -> (int) (player.getLastDamage()));

    register("exp").scoreSupply(Player::getTotalExperience);
    register("xp_to_level").scoreSupply(Player::getExpToLevel);


    register("helmet").scoreSupply(player -> calculateDurability(player.getInventory().getHelmet()));
    register("boots").scoreSupply(player -> calculateDurability(player.getInventory().getBoots()));
    register("leggings").scoreSupply(player -> calculateDurability(player.getInventory().getLeggings()));
    register("chestplate").scoreSupply(player -> calculateDurability(player.getInventory().getChestplate()));

    register("chestplate").scoreSupply(player -> (int) player.getWorld().getTime());
}
 
Example #4
Source File: AbstractChunkCacheMiddleExplosion.java    From ProtocolSupport with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
protected void handleReadData() {
	int xOrigin = NumberConversions.floor(x);
	x = xOrigin;
	int yOrigin = NumberConversions.floor(y);
	y = yOrigin;
	int zOrigin = NumberConversions.floor(z);
	z = zOrigin;
	for (Position block : blocks) {
		int xB = xOrigin + block.getX();
		int yB = yOrigin + block.getY();
		int zB = zOrigin + block.getZ();
		CachedChunk chunk = chunkCache.get(new ChunkCoord(xB >> 4, zB >> 4));
		if (chunk != null) {
			chunk.setBlock(yB >> 4, CachedChunk.getBlockIndex(xB & 0xF, yB & 0xF, zB & 0xF), (short) 0);
		}
	}
}
 
Example #5
Source File: Items.java    From TabooLib with MIT License 5 votes vote down vote up
public static Enchantment asEnchantment(String enchant) {
    try {
        Enchantment enchantment = Enchantment.getByName(enchant);
        return enchantment != null ? enchantment : Enchantment.getById(NumberConversions.toInt(enchant));
    } catch (Throwable e) {
        return null;
    }
}
 
Example #6
Source File: CronusParser.java    From TabooLib with MIT License 5 votes vote down vote up
public static ItemStack toItemStack(Object in) {
    String type = null;
    String name = null;
    String lore = null;
    int damage = -1;
    int amount = 1;
    for (String v : String.valueOf(in).split(",")) {
        if (v.toLowerCase().startsWith("type=")) {
            type = v.substring("type=".length());
        } else if (v.toLowerCase().startsWith("t=")) {
            type = v.substring("t=".length());
        } else if (v.toLowerCase().startsWith("name=")) {
            name = v.substring("name=".length());
        } else if (v.toLowerCase().startsWith("n=")) {
            name = v.substring("n=".length());
        } else if (v.toLowerCase().startsWith("lore=")) {
            lore = v.substring("lore=".length());
        } else if (v.toLowerCase().startsWith("l=")) {
            lore = v.substring("l=".length());
        } else if (v.toLowerCase().startsWith("damage=")) {
            damage = NumberConversions.toInt(v.substring("damage=".length()));
        } else if (v.toLowerCase().startsWith("d=")) {
            damage = NumberConversions.toInt(v.substring("d=".length()));
        } else if (v.toLowerCase().startsWith("amount=")) {
            amount = NumberConversions.toInt(v.substring("amount=".length()));
        } else if (v.toLowerCase().startsWith("a=")) {
            amount = NumberConversions.toInt(v.substring("a=".length()));
        } else {
            type = v;
        }
    }
    return new ItemStack(type, name, lore, damage, amount);
}
 
Example #7
Source File: CronusParser.java    From TabooLib with MIT License 5 votes vote down vote up
public static org.bukkit.Location toBukkitLocation(Object in) {
    String[] v = String.valueOf(in).split(",");
    return new org.bukkit.Location(
            v.length > 0 ? Bukkit.getWorld(v[0]) : Bukkit.getWorlds().iterator().next(),
            v.length > 1 ? NumberConversions.toDouble(v[1]) : 0,
            v.length > 2 ? NumberConversions.toDouble(v[2]) : 0,
            v.length > 3 ? NumberConversions.toDouble(v[3]) : 0,
            v.length > 4 ? NumberConversions.toFloat(v[4]) : 0,
            v.length > 5 ? NumberConversions.toFloat(v[5]) : 0);
}
 
Example #8
Source File: TLocaleBossBar.java    From TabooLib with MIT License 5 votes vote down vote up
public static TLocaleBossBar valueOf(Map<String, Object> map) {
    return new TLocaleBossBar(
            map.getOrDefault("text", "§4* Invalid Text*").toString(),
            getColor(String.valueOf(map.get("color"))),
            getStyle(String.valueOf(map.get("style"))),
            NumberConversions.toFloat(map.getOrDefault("progress", 1)),
            NumberConversions.toInt(map.getOrDefault("timeout", 20)),
            NumberConversions.toInt(map.getOrDefault("timeout-interval", 2)),
            isPlaceholderEnabled(map));
}
 
Example #9
Source File: TLocaleJson.java    From TabooLib with MIT License 5 votes vote down vote up
private static void formatNode(Map<String, Object> section, TellrawJson pageJson, String text, String node) {
    if (section.containsKey(node)) {
        try {
            Map<String, Object> args = (Map<String, Object>) section.get(node);
            // 文本
            pageJson.append(args.getOrDefault("text", text).toString());
            // 功能
            if (args.containsKey("hover")) {
                pageJson.hoverText(args.get("hover").toString());
            }
            if (args.containsKey("suggest")) {
                pageJson.clickSuggest(args.get("suggest").toString());
            }
            if (args.containsKey("command")) {
                pageJson.clickCommand(args.get("command").toString());
            }
            if (args.containsKey("page")) {
                pageJson.clickChangePage(NumberConversions.toInt(args.get("page").toString()));
            }
            if (args.containsKey("url")) {
                pageJson.clickOpenURL(args.get("url").toString());
            }
        } catch (Exception e) {
            TLocale.Logger.error("LOCALE.BOOK-ARGUMENTS-IDENTIFICATION-FAILED", e.toString());
        }
    } else {
        pageJson.append("§4* Invalid Argument *");
    }
}
 
Example #10
Source File: Items.java    From TabooLib with MIT License 5 votes vote down vote up
public static Material asMaterial(String args) {
    if (CronusUtils.isInt(args)) {
        try {
            return Material.getMaterial(NumberConversions.toInt(args));
        } catch (Throwable ignored) {
            return Materials.matchMaterials(NumberConversions.toInt(args), (byte) -1).orElse(Materials.STONE).parseMaterial();
        }
    } else {
        return Materials.matchMaterials(args.toUpperCase()).orElse(Materials.STONE).parseMaterial();
    }
}
 
Example #11
Source File: Items.java    From TabooLib with MIT License 5 votes vote down vote up
public static Color asColor(String color) {
    try {
        String[] v = color.split("-");
        return Color.fromRGB(NumberConversions.toInt(v[0]), NumberConversions.toInt(v[1]), NumberConversions.toInt(v[2]));
    } catch (Throwable e) {
        return Color.fromRGB(0, 0, 0);
    }
}
 
Example #12
Source File: Effects.java    From TabooLib with MIT License 5 votes vote down vote up
public static Effects parse(String in) {
    TMap map = TMap.parse(in);
    Effects effects = Effects.create(parseParticle(map.getName()), null);
    for (Map.Entry<String, String> entry : map.getContent().entrySet()) {
        switch (entry.getKey()) {
            case "offset":
            case "o":
                Double[] offset = Arrays.stream(entry.getValue().split(",")).map(NumberConversions::toDouble).toArray(Double[]::new);
                effects.offset(new double[] {offset.length > 0 ? offset[0] : 0, offset.length > 1 ? offset[1] : 0, offset.length > 2 ? offset[2] : 0});
                break;
            case "speed":
            case "s":
                effects.speed(NumberConversions.toDouble(entry.getValue()));
                break;
            case "range":
            case "r":
                effects.range(NumberConversions.toDouble(entry.getValue()));
                break;
            case "count":
            case "c":
            case "amount":
            case "a":
                effects.count(NumberConversions.toInt(entry.getValue()));
                break;
            case "data":
            case "d":
                String[] data = entry.getValue().split(":");
                if (effects.particle.getDataType().equals(ItemStack.class)) {
                    effects.data(new ItemStack(Items.asMaterial(data[0]), 1, data.length > 1 ? NumberConversions.toShort(data[1]) : 0));
                } else if (effects.particle.getDataType().equals(MaterialData.class)) {
                    effects.data(new MaterialData(Items.asMaterial(data[0]), data.length > 1 ? NumberConversions.toByte(data[1]) : 0));
                } else if (effects.particle == Particle.REDSTONE) {
                    effects.data(new ColorData(Color.fromRGB(NumberConversions.toInt(data[0])), NumberConversions.toInt(data[1])));
                }
                break;
        }
    }
    return effects;
}
 
Example #13
Source File: Items.java    From TabooLib with MIT License 5 votes vote down vote up
public static PotionEffectType asPotionEffectType(String potion) {
    try {
        PotionEffectType type = PotionEffectType.getByName(potion);
        return type != null ? type : PotionEffectType.getById(NumberConversions.toInt(potion));
    } catch (Throwable e) {
        return null;
    }
}
 
Example #14
Source File: ParticlesTask.java    From WorldEditSelectionVisualizer with MIT License 5 votes vote down vote up
@Override
public void run() {
    boolean needWand = plugin.getConfig().getBoolean("need-we-wand");
    double maxDistanceSquared = NumberConversions.square(config.getViewDistance());
    ParticleData particleData = config.getParticleData();

    for (Player player : Bukkit.getOnlinePlayers()) {
        PlayerVisualizerInfos visualizerInfo = plugin.getPlayerInfos(player);

        PlayerSelection playerSelection = visualizerInfo.getSelection(type).orElse(null);

        if (playerSelection == null) {
            continue;
        }

        playerSelection.checkExpireTime();
        SelectionPoints selectionPoints = playerSelection.getSelectionPoints();

        if (selectionPoints == null || (needWand && !visualizerInfo.isHoldingSelectionItem())) {
            continue;
        }

        Collection<Vector3d> vectors = primary ? selectionPoints.primary() : selectionPoints.secondary();

        Vector3d location = new Vector3d(player.getLocation().toVector());
        Vector3d origin = (type != SelectionType.CLIPBOARD) ? Vector3d.ZERO : location.subtract(selectionPoints.origin()).floor();

        for (Vector3d vector : vectors) {
            double x = vector.getX() + origin.getX();
            double y = vector.getY() + origin.getY();
            double z = vector.getZ() + origin.getZ();

            if (location.distanceSquared(x, y, z) > maxDistanceSquared) {
                continue;
            }

            FastParticle.spawnParticle(player, particleData.getType(), x, y, z, 1, 0, 0, 0, 0, particleData.getData());
        }
    }
}
 
Example #15
Source File: BukkitGlobalVariables.java    From ScoreboardStats with MIT License 5 votes vote down vote up
@Override
public void register() {
    register("tps")
            .scoreSupply(() -> NumberConversions.round(TicksPerSecondTask.getLastTicks()));

    register("online")
            .scoreSupply(() -> Bukkit.getOnlinePlayers().size())
            .eventScore(PlayerJoinEvent.class, () -> Bukkit.getOnlinePlayers().size())
            .eventScore(PlayerQuitEvent.class, () -> Bukkit.getOnlinePlayers().size() - 1);

    register("max_player")
            .scoreSupply(Bukkit::getMaxPlayers)
            .constant();
}
 
Example #16
Source File: CraftconomyVariables.java    From ScoreboardStats with MIT License 5 votes vote down vote up
@Override
public void register() {
    if (Common.isInitialized()) {
        for (String currencyName : currencyManager.getCurrencyNames()) {
            register("money_" + currencyName)
                    .scoreSupply(player -> {
                        Currency currency = currencyManager.getCurrency(currencyName);
                        double balance = accountManager.getAccount(player.getWorld().getName(), false)
                                .getBalance(player.getWorld().getName(), currencyName);
                        return NumberConversions.round(balance);
                    });
        }
    }
}
 
Example #17
Source File: PlayerStats.java    From ScoreboardStats with MIT License 5 votes vote down vote up
/**
 * Get the current kill-death-ratio rounded
 *
 * @return the kill death ratio rounded to an integer
 */
public int getKdr() {
    //We can't divide by zero
    if (deaths == 0) {
        return kills;
    } else {
        //Triggers float division to have decimals
        return NumberConversions.round(kills / (float) deaths);
    }
}
 
Example #18
Source File: Location.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Required method for deserialization
 *
 * @param args map to deserialize
 * @return deserialized location
 * @throws IllegalArgumentException if the world don't exists
 * @see ConfigurationSerializable
 */
public static Location deserialize(Map<String, Object> args) {
    World world = Bukkit.getWorld((String) args.get("world"));
    if (world == null) {
        throw new IllegalArgumentException("unknown world");
    }

    return new Location(world, NumberConversions.toDouble(args.get("x")), NumberConversions.toDouble(args.get("y")), NumberConversions.toDouble(args.get("z")), NumberConversions.toFloat(args.get("yaw")), NumberConversions.toFloat(args.get("pitch")));
}
 
Example #19
Source File: Location.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets the {@link #getYaw() yaw} and {@link #getPitch() pitch} to point
 * in the direction of the vector.
 *
 * @param vector the direction vector
 * @return the same location
 */
public Location setDirection(Vector vector) {
    /*
     * Sin = Opp / Hyp
     * Cos = Adj / Hyp
     * Tan = Opp / Adj
     *
     * x = -Opp
     * z = Adj
     */
    final double _2PI = 2 * Math.PI;
    final double x = vector.getX();
    final double z = vector.getZ();

    if (x == 0 && z == 0) {
        pitch = vector.getY() > 0 ? -90 : 90;
        return this;
    }

    double theta = Math.atan2(-x, z);
    yaw = (float) Math.toDegrees((theta + _2PI) % _2PI);

    double x2 = NumberConversions.square(x);
    double z2 = NumberConversions.square(z);
    double xz = Math.sqrt(x2 + z2);
    pitch = (float) Math.toDegrees(Math.atan(-vector.getY() / xz));

    return this;
}
 
Example #20
Source File: Location.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get the squared distance between this location and another.
 *
 * @param o The other location
 * @return the distance
 * @throws IllegalArgumentException for differing worlds
 * @see Vector
 */
public double distanceSquared(Location o) {
    if (o == null) {
        throw new IllegalArgumentException("Cannot measure distance to a null location");
    } else if (o.getWorld() == null || getWorld() == null) {
        throw new IllegalArgumentException("Cannot measure distance to a null world");
    } else if (o.getWorld() != getWorld()) {
        throw new IllegalArgumentException("Cannot measure distance between " + getWorld().getName() + " and " + o.getWorld().getName());
    }

    return NumberConversions.square(x - o.x) + NumberConversions.square(y - o.y) + NumberConversions.square(z - o.z);
}
 
Example #21
Source File: Location.java    From Kettle with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check if each component of this Location is finite.
 *
 * @throws IllegalArgumentException if any component is not finite
 */
public void checkFinite() throws IllegalArgumentException {
    NumberConversions.checkFinite(x, "x not finite");
    NumberConversions.checkFinite(y, "y not finite");
    NumberConversions.checkFinite(z, "z not finite");
    NumberConversions.checkFinite(pitch, "pitch not finite");
    NumberConversions.checkFinite(yaw, "yaw not finite");
}
 
Example #22
Source File: CraftEnderDragonPart.java    From Thermos with GNU General Public License v3.0 4 votes vote down vote up
@Deprecated
public int _INVALID_getMaxHealth() {
    return NumberConversions.ceil(getMaxHealth());
}
 
Example #23
Source File: TMap.java    From TabooLib with MIT License 4 votes vote down vote up
public double getDouble(String[] key, double def) {
    return Arrays.stream(key).filter(content::containsKey).mapToDouble(i -> NumberConversions.toDouble(content.get(i))).findFirst().orElse(def);
}
 
Example #24
Source File: ListenerCommand.java    From TabooLib with MIT License 4 votes vote down vote up
private static int orInt(List<String> list, int index, int def) {
    return list.size() > index ? NumberConversions.toInt(list.get(index)) : def;
}
 
Example #25
Source File: ListenerCommand.java    From TabooLib with MIT License 4 votes vote down vote up
private static double orDob(List<String> list, int index, double def) {
    return list.size() > index ? NumberConversions.toDouble(list.get(index)) : def;
}
 
Example #26
Source File: MetadataValueAdapter.java    From Kettle with GNU General Public License v3.0 4 votes vote down vote up
public short asShort() {
    return NumberConversions.toShort(value());
}
 
Example #27
Source File: CraftMinecart.java    From Thermos with GNU General Public License v3.0 4 votes vote down vote up
@Deprecated
public int _INVALID_getDamage() {
    return NumberConversions.ceil(getDamage());
}
 
Example #28
Source File: CraftLivingEntity.java    From Thermos with GNU General Public License v3.0 4 votes vote down vote up
@Deprecated
public int _INVALID_getLastDamage() {
    return NumberConversions.ceil(getLastDamage());
}
 
Example #29
Source File: CraftLivingEntity.java    From Thermos with GNU General Public License v3.0 4 votes vote down vote up
@Deprecated
public int _INVALID_getHealth() {
    return NumberConversions.ceil(getHealth());
}
 
Example #30
Source File: CraftLivingEntity.java    From Thermos with GNU General Public License v3.0 4 votes vote down vote up
@Deprecated
public int _INVALID_getMaxHealth() {
    return NumberConversions.ceil(getMaxHealth());
}