Search in sources :

Example 11 with Property

use of net.aufdemrand.denizencore.objects.properties.Property in project Denizen-For-Bukkit by DenizenScript.

the class dNPC method adjust.

@Override
public void adjust(Mechanism mechanism) {
    Element value = mechanism.getValue();
    // -->
    if (mechanism.matches("set_assignment") && mechanism.requireObject(dScript.class)) {
        getAssignmentTrait().setAssignment(value.asType(dScript.class).getName(), null);
    }
    // -->
    if (mechanism.matches("remove_assignment")) {
        getAssignmentTrait().removeAssignment(null);
    }
    // -->
    if (mechanism.matches("set_nickname")) {
        getNicknameTrait().setNickname(value.asString());
    }
    // -->
    if (mechanism.matches("remove_nickname")) {
        getNicknameTrait().removeNickname();
    }
    // -->
    if (mechanism.matches("set_entity_type") && mechanism.requireObject(dEntity.class)) {
        getCitizen().setBukkitEntityType(value.asType(dEntity.class).getBukkitEntityType());
    }
    // -->
    if (mechanism.matches("name") || mechanism.matches("set_name")) {
        getCitizen().setName(value.asString().length() > 64 ? value.asString().substring(0, 64) : value.asString());
    }
    // -->
    if (mechanism.matches("owner")) {
        getCitizen().getTrait(Owner.class).setOwner(value.asString());
    }
    // -->
    if (mechanism.matches("skin_blob")) {
        if (!mechanism.hasValue()) {
            getCitizen().data().remove(NPC.PLAYER_SKIN_TEXTURE_PROPERTIES_METADATA);
            getCitizen().data().remove(NPC.PLAYER_SKIN_TEXTURE_PROPERTIES_SIGN_METADATA);
        } else {
            String[] dat = mechanism.getValue().asString().split(";");
            getCitizen().data().setPersistent(NPC.PLAYER_SKIN_TEXTURE_PROPERTIES_METADATA, dat[0]);
            getCitizen().data().setPersistent(NPC.PLAYER_SKIN_TEXTURE_PROPERTIES_SIGN_METADATA, dat.length > 0 ? dat[1] : null);
        }
        if (getCitizen().isSpawned()) {
            getCitizen().despawn(DespawnReason.PENDING_RESPAWN);
            getCitizen().spawn(getCitizen().getStoredLocation());
        }
    }
    // -->
    if (mechanism.matches("skin")) {
        if (!mechanism.hasValue()) {
            getCitizen().data().remove(NPC.PLAYER_SKIN_UUID_METADATA);
        } else {
            getCitizen().data().setPersistent(NPC.PLAYER_SKIN_UUID_METADATA, mechanism.getValue().asString());
        }
        if (getCitizen().isSpawned()) {
            getCitizen().despawn(DespawnReason.PENDING_RESPAWN);
            getCitizen().spawn(getCitizen().getStoredLocation());
        }
    }
    // -->
    if (mechanism.matches("item_type") && mechanism.requireObject(dItem.class)) {
        dItem item = mechanism.getValue().asType(dItem.class);
        Material mat = item.getMaterial().getMaterial();
        int data = item.getMaterial().getData((byte) 0);
        switch(getEntity().getType()) {
            case DROPPED_ITEM:
                ((org.bukkit.entity.Item) getEntity()).getItemStack().setType(mat);
                //((ItemController.ItemNPC) getEntity()).setType(mat, data);
                break;
            case ITEM_FRAME:
                ((ItemFrame) getEntity()).getItem().setType(mat);
                //((ItemFrameController.ItemFrameNPC) getEntity()).setType(mat, data);
                break;
            case FALLING_BLOCK:
                //((FallingBlockController.FallingBlockNPC) getEntity()).setType(mat, data);
                break;
            default:
                dB.echoError("NPC is the not an item type!");
                break;
        }
        if (getCitizen().isSpawned()) {
            getCitizen().despawn();
            getCitizen().spawn(getCitizen().getStoredLocation());
        }
    }
    // -->
    if (mechanism.matches("spawn")) {
        if (mechanism.requireObject("Invalid dLocation specified. Assuming last known NPC location.", dLocation.class)) {
            getCitizen().spawn(value.asType(dLocation.class));
        } else {
            getCitizen().spawn(getCitizen().getStoredLocation());
        }
    }
    // -->
    if (mechanism.matches("range") && mechanism.requireFloat()) {
        getCitizen().getNavigator().getDefaultParameters().range(mechanism.getValue().asFloat());
    }
    // -->
    if (mechanism.matches("attack_range") && mechanism.requireFloat()) {
        getCitizen().getNavigator().getDefaultParameters().attackRange(mechanism.getValue().asFloat());
    }
    // -->
    if (mechanism.matches("speed") && mechanism.requireFloat()) {
        getCitizen().getNavigator().getDefaultParameters().speedModifier(mechanism.getValue().asFloat());
    }
    // -->
    if (mechanism.matches("despawn")) {
        getCitizen().despawn(DespawnReason.PLUGIN);
    }
    // -->
    if (mechanism.matches("set_protected") && mechanism.requireBoolean()) {
        getCitizen().setProtected(value.asBoolean());
    }
    // -->
    if (mechanism.matches("lookclose") && mechanism.requireBoolean()) {
        getLookCloseTrait().lookClose(value.asBoolean());
    }
    // -->
    if (mechanism.matches("set_examiner")) {
        if (mechanism.getValue().toString().equalsIgnoreCase("default")) {
            getNavigator().getLocalParameters().clearExaminers();
            getNavigator().getLocalParameters().examiner(new MinecraftBlockExaminer());
        } else if (mechanism.getValue().toString().equalsIgnoreCase("fly")) {
            getNavigator().getLocalParameters().clearExaminers();
            getNavigator().getLocalParameters().examiner(new FlyingBlockExaminer());
        } else if (mechanism.getValue().toString().equalsIgnoreCase("path")) {
            getNavigator().getLocalParameters().clearExaminers();
            getNavigator().getLocalParameters().examiner(new PathBlockExaminer(this, null));
        }
    }
    // -->
    if (mechanism.matches("teleport_on_stuck") && mechanism.requireBoolean()) {
        if (value.asBoolean()) {
            getNavigator().getDefaultParameters().stuckAction(TeleportStuckAction.INSTANCE);
        } else {
            getNavigator().getDefaultParameters().stuckAction(null);
        }
    }
    // -->
    if (mechanism.matches("set_distance") && mechanism.requireDouble()) {
        getNavigator().getDefaultParameters().distanceMargin(mechanism.getValue().asDouble());
    }
    // -->
    if (mechanism.matches("add_waypoint") && mechanism.requireObject(dLocation.class)) {
        if (!getCitizen().hasTrait(Waypoints.class)) {
            getCitizen().addTrait(Waypoints.class);
        }
        Waypoints wp = getCitizen().getTrait(Waypoints.class);
        if ((wp.getCurrentProvider() instanceof WaypointProvider.EnumerableWaypointProvider)) {
            ((List<Waypoint>) ((WaypointProvider.EnumerableWaypointProvider) wp.getCurrentProvider()).waypoints()).add(new Waypoint(value.asType(dLocation.class)));
        }
    }
    // Iterate through this object's properties' mechanisms
    for (Property property : PropertyParser.getProperties(this)) {
        property.adjust(mechanism);
        if (mechanism.fulfilled()) {
            break;
        }
    }
    // Pass along to dEntity mechanism handler if not already handled.
    if (!mechanism.fulfilled()) {
        if (isSpawned()) {
            new dEntity(getEntity()).adjust(mechanism);
        } else {
            mechanism.reportInvalid();
        }
    }
}
Also used : MinecraftBlockExaminer(net.citizensnpcs.api.astar.pathfinder.MinecraftBlockExaminer) Waypoints(net.citizensnpcs.trait.waypoint.Waypoints) PathBlockExaminer(net.aufdemrand.denizen.npc.examiners.PathBlockExaminer) Owner(net.citizensnpcs.api.trait.trait.Owner) Material(org.bukkit.Material) Waypoint(net.citizensnpcs.trait.waypoint.Waypoint) WaypointProvider(net.citizensnpcs.trait.waypoint.WaypointProvider) FlyingBlockExaminer(net.citizensnpcs.api.astar.pathfinder.FlyingBlockExaminer) ArrayList(java.util.ArrayList) List(java.util.List) Waypoint(net.citizensnpcs.trait.waypoint.Waypoint) Property(net.aufdemrand.denizencore.objects.properties.Property)

Example 12 with Property

use of net.aufdemrand.denizencore.objects.properties.Property in project Denizen-For-Bukkit by DenizenScript.

the class dPlayer method getAttribute.

@Override
public String getAttribute(Attribute attribute) {
    if (attribute == null) {
        return null;
    }
    if (offlinePlayer == null) {
        return null;
    }
    // Defined in dEntity
    if (attribute.startsWith("is_player")) {
        return Element.TRUE.getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("debug.log")) {
        dB.log(debug());
        return Element.TRUE.getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("debug.no_color")) {
        return new Element(ChatColor.stripColor(debug())).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("debug")) {
        return new Element(debug()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("prefix")) {
        return new Element(prefix).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("chat_history_list")) {
        return // TODO: UUID?
        new dList(PlayerTags.playerChatHistory.get(getName())).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("chat_history")) {
        int x = 1;
        if (attribute.hasContext(1) && aH.matchesInteger(attribute.getContext(1))) {
            x = attribute.getIntContext(1);
        }
        // No playerchathistory? Return null.
        if (!PlayerTags.playerChatHistory.containsKey(getName())) {
            // TODO: UUID?
            return null;
        }
        // TODO: UUID?
        List<String> messages = PlayerTags.playerChatHistory.get(getName());
        if (messages.size() < x || x < 1) {
            return null;
        }
        return new Element(messages.get(x - 1)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("flag") && attribute.hasContext(1)) {
        String flag_name = attribute.getContext(1);
        if (attribute.getAttribute(2).equalsIgnoreCase("is_expired") || attribute.startsWith("isexpired")) {
            return new Element(!FlagManager.playerHasFlag(this, flag_name)).getAttribute(attribute.fulfill(2));
        }
        if (attribute.getAttribute(2).equalsIgnoreCase("size") && !FlagManager.playerHasFlag(this, flag_name)) {
            return new Element(0).getAttribute(attribute.fulfill(2));
        }
        if (FlagManager.playerHasFlag(this, flag_name)) {
            FlagManager.Flag flag = DenizenAPI.getCurrentInstance().flagManager().getPlayerFlag(this, flag_name);
            return new dList(flag.toString(), true, flag.values()).getAttribute(attribute.fulfill(1));
        }
        return new Element(identify()).getAttribute(attribute);
    }
    // -->
    if (attribute.startsWith("has_flag") && attribute.hasContext(1)) {
        String flag_name = attribute.getContext(1);
        return new Element(FlagManager.playerHasFlag(this, flag_name)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("list_flags")) {
        dList allFlags = new dList(DenizenAPI.getCurrentInstance().flagManager().listPlayerFlags(this));
        dList searchFlags = null;
        if (!allFlags.isEmpty() && attribute.hasContext(1)) {
            searchFlags = new dList();
            String search = attribute.getContext(1);
            if (search.startsWith("regex:")) {
                try {
                    Pattern pattern = Pattern.compile(search.substring(6), Pattern.CASE_INSENSITIVE);
                    for (String flag : allFlags) {
                        if (pattern.matcher(flag).matches()) {
                            searchFlags.add(flag);
                        }
                    }
                } catch (Exception e) {
                    dB.echoError(e);
                }
            } else {
                search = CoreUtilities.toLowerCase(search);
                for (String flag : allFlags) {
                    if (CoreUtilities.toLowerCase(flag).contains(search)) {
                        searchFlags.add(flag);
                    }
                }
            }
        }
        return searchFlags == null ? allFlags.getAttribute(attribute.fulfill(1)) : searchFlags.getAttribute(attribute.fulfill(1));
    }
    if (attribute.startsWith("current_step")) {
        String outcome = "null";
        if (attribute.hasContext(1)) {
            try {
                outcome = DenizenAPI.getCurrentInstance().getSaves().getString("Players." + getName() + ".Scripts." + dScript.valueOf(attribute.getContext(1)).getName() + ".Current Step");
            } catch (Exception e) {
                outcome = "null";
            }
        }
        return new Element(outcome).getAttribute(attribute.fulfill(1));
    }
    if (attribute.startsWith("money")) {
        if (Depends.economy != null) {
            // -->
            if (attribute.startsWith("money.currency_singular")) {
                return new Element(Depends.economy.currencyNameSingular()).getAttribute(attribute.fulfill(2));
            }
            // -->
            if (attribute.startsWith("money.currency")) {
                return new Element(Depends.economy.currencyNamePlural()).getAttribute(attribute.fulfill(2));
            }
            return new Element(Depends.economy.getBalance(getOfflinePlayer())).getAttribute(attribute.fulfill(1));
        } else {
            if (!attribute.hasAlternative()) {
                dB.echoError("No economy loaded! Have you installed Vault and a compatible economy plugin?");
            }
            return null;
        }
    }
    if (attribute.startsWith("target")) {
        int range = 50;
        int attribs = 1;
        // -->
        if (attribute.getAttribute(2).startsWith("within") && attribute.hasContext(2) && aH.matchesInteger(attribute.getContext(2))) {
            attribs = 2;
            range = attribute.getIntContext(2);
        }
        List<Entity> entities = getPlayerEntity().getNearbyEntities(range, range, range);
        ArrayList<LivingEntity> possibleTargets = new ArrayList<LivingEntity>();
        for (Entity entity : entities) {
            if (entity instanceof LivingEntity) {
                // if we have a context for entity types, check the entity
                if (attribute.hasContext(1)) {
                    String context = attribute.getContext(1);
                    if (CoreUtilities.toLowerCase(context).startsWith("li@")) {
                        context = context.substring(3);
                    }
                    for (String ent : context.split("\\|")) {
                        boolean valid = false;
                        if (ent.equalsIgnoreCase("npc") && dEntity.isCitizensNPC(entity)) {
                            valid = true;
                        } else if (dEntity.matches(ent)) {
                            // only accept generic entities that are not NPCs
                            if (dEntity.valueOf(ent).isGeneric()) {
                                if (dEntity.isCitizensNPC(entity)) {
                                    valid = true;
                                }
                            } else {
                                valid = true;
                            }
                        }
                        if (valid) {
                            possibleTargets.add((LivingEntity) entity);
                        }
                    }
                } else {
                    // no entity type specified
                    possibleTargets.add((LivingEntity) entity);
                    entity.getType();
                }
            }
        }
        // Find the valid target
        BlockIterator bi;
        try {
            bi = new BlockIterator(getPlayerEntity(), range);
        } catch (IllegalStateException e) {
            return null;
        }
        Block b;
        Location l;
        int bx, by, bz;
        double ex, ey, ez;
        // Loop through player's line of sight
        while (bi.hasNext()) {
            b = bi.next();
            bx = b.getX();
            by = b.getY();
            bz = b.getZ();
            if (b.getType() != Material.AIR) {
                // Line of sight is broken
                break;
            } else {
                // Check for entities near this block in the line of sight
                for (LivingEntity possibleTarget : possibleTargets) {
                    l = possibleTarget.getLocation();
                    ex = l.getX();
                    ey = l.getY();
                    ez = l.getZ();
                    if ((bx - .50 <= ex && ex <= bx + 1.50) && (bz - .50 <= ez && ez <= bz + 1.50) && (by - 1 <= ey && ey <= by + 2.5)) {
                        // Entity is close enough, so return it
                        return new dEntity(possibleTarget).getDenizenObject().getAttribute(attribute.fulfill(attribs));
                    }
                }
            }
        }
        return null;
    }
    // workaround for <e@entity.list_effects>
    if (attribute.startsWith("list_effects")) {
        dList effects = new dList();
        for (PotionEffect effect : getPlayerEntity().getActivePotionEffects()) {
            effects.add(effect.getType().getName() + "," + effect.getAmplifier() + "," + effect.getDuration() + "t");
        }
        return effects.getAttribute(attribute.fulfill(1));
    }
    if (attribute.startsWith("list")) {
        dB.echoError("DO NOT USE PLAYER.LIST AS A TAG, please use <server.list_online_players> and related tags!");
        List<String> players = new ArrayList<String>();
        if (attribute.startsWith("list.online")) {
            for (Player player : Bukkit.getOnlinePlayers()) {
                players.add(player.getName());
            }
            return new dList(players).getAttribute(attribute.fulfill(2));
        } else if (attribute.startsWith("list.offline")) {
            for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
                if (!player.isOnline()) {
                    players.add("p@" + player.getUniqueId().toString());
                }
            }
            return new dList(players).getAttribute(attribute.fulfill(2));
        } else {
            for (OfflinePlayer player : Bukkit.getOfflinePlayers()) {
                players.add("p@" + player.getUniqueId().toString());
            }
            return new dList(players).getAttribute(attribute.fulfill(1));
        }
    }
    if (attribute.startsWith("name") && !isOnline()) // This can be parsed later with more detail if the player is online, so only check for offline.
    {
        return new Element(getName()).getAttribute(attribute.fulfill(1));
    } else if (attribute.startsWith("uuid") && !isOnline()) // This can be parsed later with more detail if the player is online, so only check for offline.
    {
        return new Element(offlinePlayer.getUniqueId().toString()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("type")) {
        return new Element("Player").getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("save_name")) {
        return new Element(getSaveName()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("bed_spawn")) {
        if (getOfflinePlayer().getBedSpawnLocation() == null) {
            return null;
        }
        return new dLocation(getOfflinePlayer().getBedSpawnLocation()).getAttribute(attribute.fulfill(1));
    }
    if (attribute.startsWith("location") && !isOnline()) {
        return getLocation().getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("first_played")) {
        attribute = attribute.fulfill(1);
        if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) {
            return new Element(getOfflinePlayer().getFirstPlayed()).getAttribute(attribute.fulfill(1));
        }
        return new Duration(getOfflinePlayer().getFirstPlayed() / 50).getAttribute(attribute);
    }
    // -->
    if (attribute.startsWith("has_played_before")) {
        return new Element(true).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("health.is_scaled")) {
        return new Element(getPlayerEntity().isHealthScaled()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("health.scale")) {
        return new Element(getPlayerEntity().getHealthScale()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("exhaustion")) {
        return new Element(getPlayerEntity().getExhaustion()).getAttribute(attribute.fulfill(1));
    }
    // Handle dEntity oxygen tags here to allow getting them when the player is offline
    if (attribute.startsWith("oxygen.max")) {
        return new Duration((long) getMaximumAir()).getAttribute(attribute.fulfill(2));
    }
    if (attribute.startsWith("oxygen")) {
        return new Duration((long) getRemainingAir()).getAttribute(attribute.fulfill(1));
    }
    // Same with health tags
    if (attribute.startsWith("health.formatted")) {
        return EntityHealth.getHealthFormatted(new dEntity(getPlayerEntity()), attribute);
    }
    if (attribute.startsWith("health.percentage")) {
        double maxHealth = getPlayerEntity().getMaxHealth();
        if (attribute.hasContext(2)) {
            maxHealth = attribute.getIntContext(2);
        }
        return new Element((getPlayerEntity().getHealth() / maxHealth) * 100).getAttribute(attribute.fulfill(2));
    }
    if (attribute.startsWith("health.max")) {
        return new Element(getMaxHealth()).getAttribute(attribute.fulfill(2));
    }
    if (attribute.matches("health")) {
        return new Element(getHealth()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_banned")) {
        BanEntry ban = Bukkit.getBanList(BanList.Type.NAME).getBanEntry(getName());
        if (ban == null) {
            return Element.FALSE.getAttribute(attribute.fulfill(1));
        } else if (ban.getExpiration() == null) {
            return Element.TRUE.getAttribute(attribute.fulfill(1));
        }
        return new Element(ban.getExpiration().after(new Date())).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_online")) {
        return new Element(isOnline()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_op")) {
        return new Element(getOfflinePlayer().isOp()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_whitelisted")) {
        return new Element(getOfflinePlayer().isWhitelisted()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("last_played")) {
        attribute = attribute.fulfill(1);
        if (attribute.startsWith("milliseconds") || attribute.startsWith("in_milliseconds")) {
            if (isOnline()) {
                return new Element(System.currentTimeMillis()).getAttribute(attribute.fulfill(1));
            }
            return new Element(getOfflinePlayer().getLastPlayed()).getAttribute(attribute.fulfill(1));
        }
        if (isOnline()) {
            return new Duration(System.currentTimeMillis() / 50).getAttribute(attribute);
        }
        return new Duration(getOfflinePlayer().getLastPlayed() / 50).getAttribute(attribute);
    }
    // -->
    if (attribute.startsWith("groups")) {
        if (Depends.permissions == null) {
            if (!attribute.hasAlternative()) {
                dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
            }
            return null;
        }
        dList list = new dList();
        // TODO: optionally specify world
        for (String group : Depends.permissions.getGroups()) {
            if (Depends.permissions.playerInGroup(null, offlinePlayer, group)) {
                list.add(group);
            }
        }
        return list.getAttribute(attribute.fulfill(1));
    }
    if (attribute.startsWith("ban_info")) {
        attribute.fulfill(1);
        BanEntry ban = Bukkit.getBanList(BanList.Type.NAME).getBanEntry(getName());
        if (ban == null) {
            return null;
        } else if (ban.getExpiration() != null && ban.getExpiration().before(new Date())) {
            return null;
        }
        // -->
        if (attribute.startsWith("expiration") && ban.getExpiration() != null) {
            return new Duration(ban.getExpiration().getTime() / 50).getAttribute(attribute.fulfill(1));
        } else // -->
        if (attribute.startsWith("reason")) {
            return new Element(ban.getReason()).getAttribute(attribute.fulfill(1));
        } else // -->
        if (attribute.startsWith("created")) {
            return new Duration(ban.getCreated().getTime() / 50).getAttribute(attribute.fulfill(1));
        }
        return null;
    }
    // -->
    if (attribute.startsWith("in_group")) {
        if (Depends.permissions == null) {
            if (!attribute.hasAlternative()) {
                dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
            }
            return null;
        }
        String group = attribute.getContext(1);
        // Non-world specific permission
        if (attribute.getAttribute(2).startsWith("global")) {
            return // TODO: Vault UUID support?
            new Element(Depends.permissions.playerInGroup((World) null, getName(), group)).getAttribute(attribute.fulfill(2));
        } else // Permission in certain world
        if (attribute.getAttribute(2).startsWith("world")) {
            return // TODO: Vault UUID support?
            new Element(Depends.permissions.playerInGroup(attribute.getContext(2), getName(), group)).getAttribute(attribute.fulfill(2));
        } else // Permission in current world
        if (isOnline()) {
            return new Element(Depends.permissions.playerInGroup(getPlayerEntity(), group)).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("permission") || attribute.startsWith("has_permission")) {
        String permission = attribute.getContext(1);
        // Non-world specific permission
        if (attribute.getAttribute(2).startsWith("global")) {
            if (Depends.permissions == null) {
                if (!attribute.hasAlternative()) {
                    dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
                }
                return null;
            }
            return // TODO: Vault UUID support?
            new Element(Depends.permissions.has((World) null, getName(), permission)).getAttribute(attribute.fulfill(2));
        } else // Permission in certain world
        if (attribute.getAttribute(2).startsWith("world")) {
            if (Depends.permissions == null) {
                if (!attribute.hasAlternative()) {
                    dB.echoError("No permission system loaded! Have you installed Vault and a compatible permissions plugin?");
                }
                return null;
            }
            return // TODO: Vault UUID support?
            new Element(Depends.permissions.has(attribute.getContext(2), getName(), permission)).getAttribute(attribute.fulfill(2));
        } else // Permission in current world
        if (isOnline()) {
            return new Element(getPlayerEntity().hasPermission(permission)).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("inventory")) {
        return getInventory().getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("enderchest")) {
        return getEnderChest().getAttribute(attribute.fulfill(1));
    }
    // Player is required to be online after this point...
    if (!isOnline()) {
        return new Element(identify()).getAttribute(attribute);
    }
    // -->
    if (attribute.startsWith("open_inventory")) {
        return new dInventory(getPlayerEntity().getOpenInventory().getTopInventory()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("item_on_cursor")) {
        return new dItem(getPlayerEntity().getItemOnCursor()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("item_in_hand.slot")) {
        return new Element(getPlayerEntity().getInventory().getHeldItemSlot() + 1).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("sidebar.lines")) {
        Sidebar sidebar = SidebarCommand.getSidebar(this);
        if (sidebar == null) {
            return null;
        }
        return new dList(sidebar.getLines()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("sidebar.title")) {
        Sidebar sidebar = SidebarCommand.getSidebar(this);
        if (sidebar == null) {
            return null;
        }
        return new Element(sidebar.getTitle()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("sidebar.scores")) {
        Sidebar sidebar = SidebarCommand.getSidebar(this);
        if (sidebar == null) {
            return null;
        }
        dList scores = new dList();
        for (int score : sidebar.getScores()) {
            scores.add(String.valueOf(score));
        }
        return scores.getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("sidebar.start")) {
        Sidebar sidebar = SidebarCommand.getSidebar(this);
        if (sidebar == null) {
            return null;
        }
        return new Element(sidebar.getStart()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("sidebar.increment")) {
        Sidebar sidebar = SidebarCommand.getSidebar(this);
        if (sidebar == null) {
            return null;
        }
        return new Element(sidebar.getIncrement()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("skin_blob")) {
        return new Element(NMSHandler.getInstance().getProfileEditor().getPlayerSkinBlob(getPlayerEntity())).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("selected_npc")) {
        if (getPlayerEntity().hasMetadata("selected")) {
            return getSelectedNPC().getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("entity") && !attribute.startsWith("entity_")) {
        return new dEntity(getPlayerEntity()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("ip") || attribute.startsWith("host_name")) {
        attribute = attribute.fulfill(1);
        // -->
        if (attribute.startsWith("address_only")) {
            return new Element(getPlayerEntity().getAddress().toString()).getAttribute(attribute.fulfill(1));
        }
        String host = getPlayerEntity().getAddress().getHostName();
        // -->
        if (attribute.startsWith("address")) {
            return new Element(getPlayerEntity().getAddress().toString()).getAttribute(attribute.fulfill(1));
        }
        return new Element(host).getAttribute(attribute);
    }
    // -->
    if (attribute.startsWith("name.display")) {
        return new Element(getPlayerEntity().getDisplayName()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("name.list")) {
        return new Element(getPlayerEntity().getPlayerListName()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("nameplate")) {
        return new Element(NMSHandler.getInstance().getProfileEditor().getPlayerName(getPlayerEntity())).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("name")) {
        return new Element(getName()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("has_finished")) {
        dScript script = dScript.valueOf(attribute.getContext(1));
        if (script == null) {
            return Element.FALSE.getAttribute(attribute.fulfill(1));
        }
        return new Element(FinishCommand.getScriptCompletes(getName(), script.getName()) > 0).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("has_failed")) {
        dScript script = dScript.valueOf(attribute.getContext(1));
        if (script == null) {
            return Element.FALSE.getAttribute(attribute.fulfill(1));
        }
        return new Element(FailCommand.getScriptFails(getName(), script.getName()) > 0).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("compass_target")) {
        Location target = getPlayerEntity().getCompassTarget();
        if (target != null) {
            return new dLocation(target).getAttribute(attribute.fulfill(1));
        }
    }
    // -->
    if (attribute.startsWith("chunk_loaded") && attribute.hasContext(1)) {
        dChunk chunk = dChunk.valueOf(attribute.getContext(1));
        if (chunk == null) {
            return null;
        }
        return new Element(hasChunkLoaded(chunk.chunk)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("can_fly") || attribute.startsWith("allowed_flight")) {
        return new Element(getPlayerEntity().getAllowFlight()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("fly_speed")) {
        return new Element(getPlayerEntity().getFlySpeed()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("food_level.formatted")) {
        double maxHunger = getPlayerEntity().getMaxHealth();
        if (attribute.hasContext(2)) {
            maxHunger = attribute.getIntContext(2);
        }
        int foodLevel = getFoodLevel();
        if (foodLevel / maxHunger < .10) {
            return new Element("starving").getAttribute(attribute.fulfill(2));
        } else if (foodLevel / maxHunger < .40) {
            return new Element("famished").getAttribute(attribute.fulfill(2));
        } else if (foodLevel / maxHunger < .75) {
            return new Element("parched").getAttribute(attribute.fulfill(2));
        } else if (foodLevel / maxHunger < 1) {
            return new Element("hungry").getAttribute(attribute.fulfill(2));
        } else {
            return new Element("healthy").getAttribute(attribute.fulfill(2));
        }
    }
    // -->
    if (attribute.startsWith("saturation")) {
        return new Element(getPlayerEntity().getSaturation()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("food_level")) {
        return new Element(getFoodLevel()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("gamemode")) {
        attribute = attribute.fulfill(1);
        // -->
        if (attribute.startsWith("id")) {
            return new Element(getPlayerEntity().getGameMode().getValue()).getAttribute(attribute.fulfill(1));
        }
        return new Element(getPlayerEntity().getGameMode().name()).getAttribute(attribute);
    }
    // -->
    if (attribute.startsWith("is_blocking")) {
        return new Element(getPlayerEntity().isBlocking()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("ping")) {
        return new Element(NMSHandler.getInstance().getPlayerHelper().getPing(getPlayerEntity())).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_flying")) {
        return new Element(getPlayerEntity().isFlying()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_sleeping")) {
        return new Element(getPlayerEntity().isSleeping()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_sneaking")) {
        return new Element(getPlayerEntity().isSneaking()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("is_sprinting")) {
        return new Element(getPlayerEntity().isSprinting()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("has_achievement")) {
        Achievement ach = Achievement.valueOf(attribute.getContext(1).toUpperCase());
        return new Element(getPlayerEntity().hasAchievement(ach)).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("statistic")) {
        Statistic statistic = Statistic.valueOf(attribute.getContext(1).toUpperCase());
        if (statistic == null) {
            return null;
        }
        // -->
        if (attribute.getAttribute(2).startsWith("qualifier")) {
            dObject obj = ObjectFetcher.pickObjectFor(attribute.getContext(2));
            try {
                if (obj instanceof dMaterial) {
                    return new Element(getPlayerEntity().getStatistic(statistic, ((dMaterial) obj).getMaterial())).getAttribute(attribute.fulfill(2));
                } else if (obj instanceof dEntity) {
                    return new Element(getPlayerEntity().getStatistic(statistic, ((dEntity) obj).getBukkitEntityType())).getAttribute(attribute.fulfill(2));
                } else {
                    return null;
                }
            } catch (Exception e) {
                dB.echoError("Invalid statistic: " + statistic + " for this player!");
                return null;
            }
        }
        try {
            return new Element(getPlayerEntity().getStatistic(statistic)).getAttribute(attribute.fulfill(1));
        } catch (Exception e) {
            dB.echoError("Invalid statistic: " + statistic + " for this player!");
            return null;
        }
    }
    // -->
    if (attribute.startsWith("time_asleep")) {
        return new Duration(getPlayerEntity().getSleepTicks() / 20).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("time")) {
        return new Element(getPlayerEntity().getPlayerTime()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("walk_speed")) {
        return new Element(getPlayerEntity().getWalkSpeed()).getAttribute(attribute.fulfill(1));
    }
    // -->
    if (attribute.startsWith("weather")) {
        if (getPlayerEntity().getPlayerWeather() != null) {
            return new Element(getPlayerEntity().getPlayerWeather().name()).getAttribute(attribute.fulfill(1));
        } else {
            return null;
        }
    }
    // -->
    if (attribute.startsWith("xp.level")) {
        return new Element(getPlayerEntity().getLevel()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("xp.to_next_level")) {
        return new Element(getPlayerEntity().getExpToLevel()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("xp.total")) {
        return new Element(getPlayerEntity().getTotalExperience()).getAttribute(attribute.fulfill(2));
    }
    // -->
    if (attribute.startsWith("xp")) {
        return new Element(getPlayerEntity().getExp() * 100).getAttribute(attribute.fulfill(1));
    }
    if (Depends.chat != null) {
        // -->
        if (attribute.startsWith("chat_prefix")) {
            String prefix = Depends.chat.getPlayerPrefix(getWorld().getName(), getOfflinePlayer());
            if (prefix == null) {
                return null;
            }
            return new Element(prefix).getAttribute(attribute.fulfill(1));
        } else // -->
        if (attribute.startsWith("chat_suffix")) {
            String suffix = Depends.chat.getPlayerSuffix(getWorld().getName(), getOfflinePlayer());
            if (suffix == null) {
                return null;
            }
            return new Element(suffix).getAttribute(attribute.fulfill(1));
        }
    }
    // Iterate through this object's properties' attributes
    for (Property property : PropertyParser.getProperties(this)) {
        String returned = property.getAttribute(attribute);
        if (returned != null) {
            return returned;
        }
    }
    return new dEntity(getPlayerEntity()).getAttribute(attribute);
}
Also used : Entity(org.bukkit.entity.Entity) LivingEntity(org.bukkit.entity.LivingEntity) BlockIterator(org.bukkit.util.BlockIterator) PotionEffect(org.bukkit.potion.PotionEffect) ArrayList(java.util.ArrayList) FlagManager(net.aufdemrand.denizen.flags.FlagManager) LivingEntity(org.bukkit.entity.LivingEntity) ImprovedOfflinePlayer(net.aufdemrand.denizen.nms.abstracts.ImprovedOfflinePlayer) Property(net.aufdemrand.denizencore.objects.properties.Property) Pattern(java.util.regex.Pattern) Player(org.bukkit.entity.Player) ImprovedOfflinePlayer(net.aufdemrand.denizen.nms.abstracts.ImprovedOfflinePlayer) Date(java.util.Date) Block(org.bukkit.block.Block) Sidebar(net.aufdemrand.denizen.nms.abstracts.Sidebar)

Example 13 with Property

use of net.aufdemrand.denizencore.objects.properties.Property in project Denizen-For-Bukkit by DenizenScript.

the class dPlayer method adjust.

@Override
public void adjust(Mechanism mechanism) {
    Element value = mechanism.getValue();
    // -->
    if (mechanism.matches("level") && mechanism.requireInteger()) {
        setLevel(value.asInt());
    }
    // -->
    if (mechanism.matches("item_slot") && mechanism.requireInteger()) {
        if (isOnline()) {
            getPlayerEntity().getInventory().setHeldItemSlot(value.asInt() - 1);
        } else {
            getNBTEditor().setItemInHand(value.asInt() - 1);
        }
    }
    // -->
    if (mechanism.matches("item_on_cursor") && mechanism.requireObject(dItem.class)) {
        getPlayerEntity().setItemOnCursor(value.asType(dItem.class).getItemStack());
    }
    // TODO: Player achievement tags.
    if (mechanism.matches("award_achievement") && mechanism.requireEnum(false, Achievement.values())) {
        getPlayerEntity().awardAchievement(Achievement.valueOf(value.asString().toUpperCase()));
    }
    // -->
    if (mechanism.matches("health_scale") && mechanism.requireDouble()) {
        getPlayerEntity().setHealthScale(value.asDouble());
    }
    // -->
    if (mechanism.matches("scale_health") && mechanism.requireBoolean()) {
        getPlayerEntity().setHealthScaled(value.asBoolean());
    }
    // Allow offline editing of health values
    if (mechanism.matches("max_health") && mechanism.requireDouble()) {
        setMaxHealth(value.asDouble());
    }
    if (mechanism.matches("health") && mechanism.requireDouble()) {
        setHealth(value.asDouble());
    }
    // -->
    if (mechanism.matches("resource_pack") || mechanism.matches("texture_pack")) {
        getPlayerEntity().setResourcePack(value.asString());
    }
    // -->
    if (mechanism.matches("saturation") && mechanism.requireFloat()) {
        getPlayerEntity().setSaturation(value.asFloat());
    }
    // -->
    if (mechanism.matches("send_map") && mechanism.requireInteger()) {
        MapView map = Bukkit.getServer().getMap((short) value.asInt());
        if (map != null) {
            getPlayerEntity().sendMap(map);
        } else {
            dB.echoError("No map found for ID " + value.asInt() + "!");
        }
    }
    // -->
    if (mechanism.matches("food_level") && mechanism.requireInteger()) {
        setFoodLevel(value.asInt());
    }
    // -->
    if (mechanism.matches("bed_spawn_location") && mechanism.requireObject(dLocation.class)) {
        setBedSpawnLocation(value.asType(dLocation.class));
    }
    // -->
    if (mechanism.matches("can_fly") && mechanism.requireBoolean()) {
        getPlayerEntity().setAllowFlight(value.asBoolean());
    }
    // -->
    if (mechanism.matches("fly_speed") && mechanism.requireFloat()) {
        setFlySpeed(value.asFloat());
    }
    // -->
    if (mechanism.matches("flying") && mechanism.requireBoolean()) {
        getPlayerEntity().setFlying(value.asBoolean());
    }
    // -->
    if (mechanism.matches("gamemode") && mechanism.requireEnum(false, GameMode.values())) {
        setGameMode(GameMode.valueOf(value.asString().toUpperCase()));
    }
    // -->
    if (mechanism.matches("kick")) {
        getPlayerEntity().kickPlayer(mechanism.getValue().asString());
    }
    // -->
    if (mechanism.matches("weather") && mechanism.requireEnum(false, WeatherType.values())) {
        getPlayerEntity().setPlayerWeather(WeatherType.valueOf(value.asString().toUpperCase()));
    }
    // -->
    if (mechanism.matches("reset_weather")) {
        getPlayerEntity().resetPlayerWeather();
    }
    // -->
    if (mechanism.matches("player_list_name")) {
        getPlayerEntity().setPlayerListName(value.asString());
    }
    // -->
    if (mechanism.matches("display_name")) {
        getPlayerEntity().setDisplayName(value.asString());
        return;
    }
    // -->
    if (mechanism.matches("show_workbench") && mechanism.requireObject(dLocation.class)) {
        getPlayerEntity().openWorkbench(mechanism.getValue().asType(dLocation.class), true);
        return;
    }
    // -->
    if (mechanism.matches("location") && mechanism.requireObject(dLocation.class)) {
        setLocation(value.asType(dLocation.class));
    }
    // -->
    if (mechanism.matches("time") && mechanism.requireInteger()) {
        getPlayerEntity().setPlayerTime(value.asInt(), true);
    }
    // -->
    if (mechanism.matches("freeze_time")) {
        if (mechanism.requireInteger("Invalid integer specified. Assuming current world time.")) {
            getPlayerEntity().setPlayerTime(value.asInt(), false);
        } else {
            getPlayerEntity().setPlayerTime(getPlayerEntity().getWorld().getTime(), false);
        }
    }
    // -->
    if (mechanism.matches("reset_time")) {
        getPlayerEntity().resetPlayerTime();
    }
    // -->
    if (mechanism.matches("walk_speed") && mechanism.requireFloat()) {
        getPlayerEntity().setWalkSpeed(value.asFloat());
    }
    // -->
    if (mechanism.matches("exhaustion") && mechanism.requireFloat()) {
        getPlayerEntity().setExhaustion(value.asFloat());
    }
    // -->
    if (mechanism.matches("show_entity") && mechanism.requireObject(dEntity.class)) {
        NMSHandler.getInstance().getEntityHelper().unhideEntity(getPlayerEntity(), value.asType(dEntity.class).getBukkitEntity());
    }
    // -->
    if (mechanism.matches("hide_entity")) {
        if (!value.asString().isEmpty()) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]", 2);
            if (split.length > 0 && new Element(split[0]).matchesType(dEntity.class)) {
                dEntity entity = value.asType(dEntity.class);
                if (!entity.isSpawned()) {
                    dB.echoError("Can't hide the unspawned entity '" + split[0] + "'!");
                } else if (split.length > 1 && new Element(split[1]).isBoolean()) {
                    NMSHandler.getInstance().getEntityHelper().hideEntity(getPlayerEntity(), entity.getBukkitEntity(), new Element(split[1]).asBoolean());
                } else {
                    NMSHandler.getInstance().getEntityHelper().hideEntity(getPlayerEntity(), entity.getBukkitEntity(), false);
                }
            } else {
                dB.echoError("'" + split[0] + "' is not a valid entity!");
            }
        }
    }
    // -->
    if (mechanism.matches("show_boss_bar")) {
        if (!value.asString().isEmpty()) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]", 2);
            if (split.length == 2 && new Element(split[0]).isDouble()) {
                NMSHandler.getInstance().getPlayerHelper().showSimpleBossBar(getPlayerEntity(), split[1], new Element(split[0]).asDouble() / 200);
            } else {
                NMSHandler.getInstance().getPlayerHelper().showSimpleBossBar(getPlayerEntity(), split[0], 1.0);
            }
        } else {
            NMSHandler.getInstance().getPlayerHelper().removeSimpleBossBar(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("fake_experience")) {
        if (!value.asString().isEmpty()) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]", 2);
            if (split.length > 0 && new Element(split[0]).isFloat()) {
                if (split.length > 1 && new Element(split[1]).isInt()) {
                    NMSHandler.getInstance().getPacketHelper().showExperience(getPlayerEntity(), new Element(split[0]).asFloat(), new Element(split[1]).asInt());
                } else {
                    NMSHandler.getInstance().getPacketHelper().showExperience(getPlayerEntity(), new Element(split[0]).asFloat(), getPlayerEntity().getLevel());
                }
            } else {
                dB.echoError("'" + split[0] + "' is not a valid decimal number!");
            }
        } else {
            NMSHandler.getInstance().getPacketHelper().resetExperience(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("fake_health")) {
        if (!value.asString().isEmpty()) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]", 3);
            if (split.length > 0 && new Element(split[0]).isFloat()) {
                if (split.length > 1 && new Element(split[1]).isInt()) {
                    if (split.length > 2 && new Element(split[2]).isFloat()) {
                        NMSHandler.getInstance().getPacketHelper().showHealth(getPlayerEntity(), new Element(split[0]).asFloat(), new Element(split[1]).asInt(), new Element(split[2]).asFloat());
                    } else {
                        NMSHandler.getInstance().getPacketHelper().showHealth(getPlayerEntity(), new Element(split[0]).asFloat(), new Element(split[1]).asInt(), getPlayerEntity().getSaturation());
                    }
                } else {
                    NMSHandler.getInstance().getPacketHelper().showHealth(getPlayerEntity(), new Element(split[0]).asFloat(), getPlayerEntity().getFoodLevel(), getPlayerEntity().getSaturation());
                }
            } else {
                dB.echoError("'" + split[0] + "' is not a valid decimal number!");
            }
        } else {
            NMSHandler.getInstance().getPacketHelper().resetHealth(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("fake_equipment")) {
        if (!value.asString().isEmpty()) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]", 3);
            if (split.length > 0 && new Element(split[0]).matchesType(dEntity.class)) {
                String slot = split[1].toUpperCase();
                if (split.length > 1 && (new Element(slot).matchesEnum(EquipmentSlot.values()) || slot.equals("MAIN_HAND") || slot.equals("BOOTS"))) {
                    if (split.length > 2 && new Element(split[2]).matchesType(dItem.class)) {
                        if (slot.equals("MAIN_HAND")) {
                            slot = "HAND";
                        } else if (slot.equals("BOOTS")) {
                            slot = "FEET";
                        }
                        NMSHandler.getInstance().getPacketHelper().showEquipment(getPlayerEntity(), new Element(split[0]).asType(dEntity.class).getLivingEntity(), EquipmentSlot.valueOf(slot), new Element(split[2]).asType(dItem.class).getItemStack());
                    } else if (split.length > 2) {
                        dB.echoError("'" + split[2] + "' is not a valid dItem!");
                    }
                } else if (split.length > 1) {
                    dB.echoError("'" + split[1] + "' is not a valid slot; must be HAND, OFF_HAND, BOOTS, LEGS, CHEST, or HEAD!");
                } else {
                    NMSHandler.getInstance().getPacketHelper().resetEquipment(getPlayerEntity(), new Element(split[0]).asType(dEntity.class).getLivingEntity());
                }
            } else {
                dB.echoError("'" + split[0] + "' is not a valid dEntity!");
            }
        }
    }
    // -->
    if (mechanism.matches("item_message")) {
        ItemChangeMessage.sendMessage(getPlayerEntity(), value.asString());
    }
    // -->
    if (mechanism.matches("show_endcredits")) {
        NMSHandler.getInstance().getPlayerHelper().showEndCredits(getPlayerEntity());
    }
    // -->
    if (mechanism.matches("spectate") && mechanism.requireObject(dEntity.class)) {
        NMSHandler.getInstance().getPacketHelper().forceSpectate(getPlayerEntity(), value.asType(dEntity.class).getBukkitEntity());
    }
    // -->
    if (mechanism.matches("open_book")) {
        NMSHandler.getInstance().getPacketHelper().openBook(getPlayerEntity(), EquipmentSlot.HAND);
    }
    // -->
    if (NMSHandler.getVersion().isAtLeast(NMSVersion.v1_9_R2) && mechanism.matches("open_offhand_book")) {
        NMSHandler.getInstance().getPacketHelper().openBook(getPlayerEntity(), EquipmentSlot.OFF_HAND);
    }
    // -->
    if (mechanism.matches("edit_sign") && mechanism.requireObject(dLocation.class)) {
        if (!NMSHandler.getInstance().getPacketHelper().showSignEditor(getPlayerEntity(), value.asType(dLocation.class))) {
            dB.echoError("Can't edit non-sign materials!");
        }
    }
    // -->
    if (mechanism.matches("tab_list_info")) {
        if (!value.asString().isEmpty()) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]", 2);
            if (split.length > 0) {
                String header = split[0];
                String footer = "";
                if (split.length > 1) {
                    footer = split[1];
                }
                NMSHandler.getInstance().getPacketHelper().showTabListHeaderFooter(getPlayerEntity(), header, footer);
            } else {
                dB.echoError("Must specify a header and footer to show!");
            }
        } else {
            NMSHandler.getInstance().getPacketHelper().resetTabListHeaderFooter(getPlayerEntity());
        }
    }
    // -->
    if (mechanism.matches("sign_update")) {
        if (!value.asString().isEmpty()) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]", 2);
            if (dLocation.matches(split[0]) && split.length > 1) {
                dList lines = dList.valueOf(split[1]);
                getPlayerEntity().sendSignChange(dLocation.valueOf(split[0]), lines.toArray(4));
            } else {
                dB.echoError("Must specify a valid location and at least one sign line!");
            }
        } else {
            dB.echoError("Must specify a valid location and at least one sign line!");
        }
    }
    // -->
    if (mechanism.matches("banner_update")) {
        if (value.asString().length() > 0) {
            String[] split = value.asString().split("[\\|" + dList.internal_escape + "]");
            List<org.bukkit.block.banner.Pattern> patterns = new ArrayList<org.bukkit.block.banner.Pattern>();
            if (split.length > 2) {
                List<String> splitList;
                for (int i = 2; i > split.length; i++) {
                    String string = split[i];
                    try {
                        splitList = CoreUtilities.split(string, '/', 2);
                        patterns.add(new org.bukkit.block.banner.Pattern(DyeColor.valueOf(splitList.get(0).toUpperCase()), PatternType.valueOf(splitList.get(1).toUpperCase())));
                    } catch (Exception e) {
                        dB.echoError("Could not apply pattern to banner: " + string);
                    }
                }
            }
            if (dLocation.matches(split[0]) && split.length > 1) {
                dLocation location = dLocation.valueOf(split[0]);
                DyeColor base;
                try {
                    base = DyeColor.valueOf(split[1].toUpperCase());
                } catch (Exception e) {
                    dB.echoError("Could not apply base color to banner: " + split[1]);
                    return;
                }
                NMSHandler.getInstance().getPacketHelper().showBannerUpdate(getPlayerEntity(), location, base, patterns);
            } else {
                dB.echoError("Must specify a valid location and a base color!");
            }
        }
    }
    // -->
    if (mechanism.matches("action_bar")) {
        NMSHandler.getInstance().getPacketHelper().sendActionBarMessage(getPlayerEntity(), value.asString());
    }
    // -->
    if (mechanism.matches("name")) {
        String name = value.asString();
        if (name.length() > 16) {
            dB.echoError("Must specify a name with no more than 16 characters.");
        } else {
            NMSHandler.getInstance().getProfileEditor().setPlayerName(getPlayerEntity(), value.asString());
        }
    }
    // -->
    if (mechanism.matches("skin")) {
        String name = value.asString();
        if (name.length() > 16) {
            dB.echoError("Must specify a name with no more than 16 characters.");
        } else {
            NMSHandler.getInstance().getProfileEditor().setPlayerSkin(getPlayerEntity(), value.asString());
        }
    }
    // -->
    if (mechanism.matches("skin_blob")) {
        NMSHandler.getInstance().getProfileEditor().setPlayerSkinBlob(getPlayerEntity(), value.asString());
    }
    // -->
    if (mechanism.matches("is_whitelisted") && mechanism.requireBoolean()) {
        getPlayerEntity().setWhitelisted(mechanism.getValue().asBoolean());
    }
    // -->
    if (mechanism.matches("is_op") && mechanism.requireBoolean()) {
        getOfflinePlayer().setOp(mechanism.getValue().asBoolean());
    }
    // -->
    if (mechanism.matches("is_banned") && mechanism.requireBoolean()) {
        getOfflinePlayer().setBanned(mechanism.getValue().asBoolean());
    }
    // -->
    if (mechanism.matches("money") && mechanism.requireDouble() && Depends.economy != null) {
        double bal = Depends.economy.getBalance(getOfflinePlayer());
        double goal = value.asDouble();
        if (goal > bal) {
            Depends.economy.depositPlayer(getOfflinePlayer(), goal - bal);
        } else if (bal > goal) {
            Depends.economy.withdrawPlayer(getOfflinePlayer(), bal - goal);
        }
    }
    if (Depends.chat != null) {
        // -->
        if (mechanism.matches("chat_prefix")) {
            Depends.chat.setPlayerPrefix(getPlayerEntity(), value.asString());
        }
        // -->
        if (mechanism.matches("chat_suffix")) {
            Depends.chat.setPlayerSuffix(getPlayerEntity(), value.asString());
        }
    }
    // Iterate through this object's properties' mechanisms
    for (Property property : PropertyParser.getProperties(this)) {
        property.adjust(mechanism);
        if (mechanism.fulfilled()) {
            break;
        }
    }
    // Pass along to dEntity mechanism handler if not already handled.
    if (!mechanism.fulfilled()) {
        Adjustable entity = new dEntity(getPlayerEntity());
        entity.adjust(mechanism);
    }
}
Also used : Pattern(java.util.regex.Pattern) org.bukkit(org.bukkit) ArrayList(java.util.ArrayList) MapView(org.bukkit.map.MapView) Property(net.aufdemrand.denizencore.objects.properties.Property)

Example 14 with Property

use of net.aufdemrand.denizencore.objects.properties.Property in project Denizen-For-Bukkit by DenizenScript.

the class dInventory method adjust.

@Override
public void adjust(Mechanism mechanism) {
    // Iterate through this object's properties' mechanisms
    for (Property property : PropertyParser.getProperties(this)) {
        property.adjust(mechanism);
        if (mechanism.fulfilled()) {
            break;
        }
    }
    if (inventory instanceof CraftingInventory) {
        CraftingInventory craftingInventory = (CraftingInventory) inventory;
        // -->
        if (mechanism.matches("matrix") && mechanism.requireObject(dList.class)) {
            List<dItem> items = mechanism.getValue().asType(dList.class).filter(dItem.class);
            ItemStack[] itemStacks = new ItemStack[9];
            for (int i = 0; i < 9 && i < items.size(); i++) {
                itemStacks[i] = items.get(i).getItemStack();
            }
            craftingInventory.setMatrix(itemStacks);
            ((Player) inventory.getHolder()).updateInventory();
        }
        // -->
        if (mechanism.matches("result") && mechanism.requireObject(dItem.class)) {
            craftingInventory.setResult(mechanism.getValue().asType(dItem.class).getItemStack());
            ((Player) inventory.getHolder()).updateInventory();
        }
    }
    if (!mechanism.fulfilled()) {
        mechanism.reportInvalid();
    }
}
Also used : CraftingInventory(org.bukkit.inventory.CraftingInventory) Player(org.bukkit.entity.Player) ImprovedOfflinePlayer(net.aufdemrand.denizen.nms.abstracts.ImprovedOfflinePlayer) ItemStack(org.bukkit.inventory.ItemStack) Property(net.aufdemrand.denizencore.objects.properties.Property)

Example 15 with Property

use of net.aufdemrand.denizencore.objects.properties.Property in project Denizen-For-Bukkit by DenizenScript.

the class dItem method getAttribute.

/////////////////
// ATTRIBUTES
/////////
@Override
public String getAttribute(Attribute attribute) {
    if (attribute == null) {
        return null;
    }
    // TODO: Scrap getAttribute, make this functionality a core system
    String attrLow = CoreUtilities.toLowerCase(attribute.getAttributeWithoutContext(1));
    TagRunnable tr = registeredTags.get(attrLow);
    if (tr != null) {
        if (!tr.name.equals(attrLow)) {
            net.aufdemrand.denizencore.utilities.debugging.dB.echoError(attribute.getScriptEntry() != null ? attribute.getScriptEntry().getResidingQueue() : null, "Using deprecated form of tag '" + tr.name + "': '" + attrLow + "'.");
        }
        return tr.run(attribute, this);
    }
    // -->
    if (attribute.startsWith("material.formatted")) {
        attribute.fulfill(1);
    }
    if (attribute.startsWith("formatted")) {
        String id = CoreUtilities.toLowerCase(getMaterial().realName()).replace('_', ' ');
        if (id.equals("air")) {
            return new Element("nothing").getAttribute(attribute.fulfill(1));
        }
        if (id.equals("ice") || id.equals("dirt")) {
            return new Element(id).getAttribute(attribute.fulfill(1));
        }
        if (getItemStack().getAmount() > 1) {
            if (id.equals("cactus")) {
                return new Element("cactuses").getAttribute(attribute.fulfill(1));
            }
            if (id.endsWith(" off")) {
                id = new String(id.substring(0, id.length() - 4));
            }
            if (id.endsWith(" on")) {
                id = new String(id.substring(0, id.length() - 3));
            }
            if (id.equals("rotten flesh") || id.equals("cooked fish") || id.equals("raw fish") || id.endsWith("s")) {
                return new Element(id).getAttribute(attribute.fulfill(1));
            }
            if (id.endsWith("y")) {
                return new Element(id.substring(0, id.length() - 1) + "ies").getAttribute(// ex: lily -> lilies
                attribute.fulfill(1));
            }
            if (id.endsWith("sh") || id.endsWith("ch")) {
                return new Element(id + "es").getAttribute(attribute.fulfill(1));
            }
            // else
            return new Element(id + "s").getAttribute(// iron sword -> iron swords
            attribute.fulfill(1));
        } else {
            if (id.equals("cactus")) {
                return new Element("a cactus").getAttribute(attribute.fulfill(1));
            }
            if (id.endsWith("s")) {
                return new Element(id).getAttribute(attribute.fulfill(1));
            }
            if (id.endsWith(" off")) {
                return new Element("a " + id.substring(0, id.length() - 4)).getAttribute(attribute.fulfill(1));
            }
            if (id.endsWith(" on")) {
                return new Element("a " + id.substring(0, id.length() - 3)).getAttribute(attribute.fulfill(1));
            }
            if (id.startsWith("a") || id.startsWith("e") || id.startsWith("i") || id.startsWith("o") || id.startsWith("u")) {
                return new Element("an " + id).getAttribute(// ex: emerald -> an emerald
                attribute.fulfill(1));
            }
            // else
            return new Element("a " + id).getAttribute(// ex: diamond -> a diamond
            attribute.fulfill(1));
        }
    }
    // Iterate through this object's properties' attributes
    for (Property property : PropertyParser.getProperties(this)) {
        String returned = property.getAttribute(attribute);
        if (returned != null) {
            return returned;
        }
    }
    return new Element(identify()).getAttribute(attribute);
}
Also used : Property(net.aufdemrand.denizencore.objects.properties.Property)

Aggregations

Property (net.aufdemrand.denizencore.objects.properties.Property)20 ArrayList (java.util.ArrayList)4 Pattern (java.util.regex.Pattern)4 FlagManager (net.aufdemrand.denizen.flags.FlagManager)3 Material (org.bukkit.Material)3 Player (org.bukkit.entity.Player)3 ItemStack (org.bukkit.inventory.ItemStack)3 PotionEffect (org.bukkit.potion.PotionEffect)3 ImprovedOfflinePlayer (net.aufdemrand.denizen.nms.abstracts.ImprovedOfflinePlayer)2 EntityHelper (net.aufdemrand.denizen.nms.interfaces.EntityHelper)2 Entity (org.bukkit.entity.Entity)2 LivingEntity (org.bukkit.entity.LivingEntity)2 CraftingInventory (org.bukkit.inventory.CraftingInventory)2 BlockIterator (org.bukkit.util.BlockIterator)2 File (java.io.File)1 java.util (java.util)1 Comparator (java.util.Comparator)1 Date (java.util.Date)1 List (java.util.List)1 BukkitScriptEntryData (net.aufdemrand.denizen.BukkitScriptEntryData)1