Search in sources :

Example 1 with GenericArguments2

use of org.lanternpowered.server.command.element.GenericArguments2 in project LanternServer by LanternPowered.

the class CommandTime method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final Map<String, Integer> presets = new HashMap<>();
    presets.put("day", 1000);
    presets.put("night", 13000);
    specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none())).child(CommandSpec.builder().arguments(new CommandElement(Text.of("value")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            final String input = args.next().toLowerCase();
            // Try to use one of the presets first
            if (presets.containsKey(input)) {
                return presets.get(input);
            }
            try {
                return Integer.parseInt(input);
            } catch (NumberFormatException ex) {
                throw args.createError(t("Expected an integer or a valid preset, but input '%s' was not", input));
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String prefix = args.nextIfPresent().orElse("");
            return presets.keySet().stream().filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
        }
    }).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        int time = args.<Integer>getOne("value").get();
        world.setWorldTime(time);
        src.sendMessage(t("commands.time.set", time));
        return CommandResult.success();
    }).build(), "set").child(CommandSpec.builder().arguments(GenericArguments.integer(Text.of("value"))).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        int time = args.<Integer>getOne("value").get();
        world.setWorldTime(world.getWorldTime() + time);
        src.sendMessage(t("commands.time.added", time));
        return CommandResult.success();
    }).build(), "add").child(CommandSpec.builder().arguments(GenericArguments2.enumValue(Text.of("value"), QueryType.class)).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        QueryType queryType = args.<QueryType>getOne("value").get();
        int result;
        switch(queryType) {
            case DAYTIME:
                result = (int) (world.getWorldTime() % Integer.MAX_VALUE);
                break;
            case GAMETIME:
                result = (int) (world.getTotalTime() % Integer.MAX_VALUE);
                break;
            case DAY:
                result = (int) (world.getTotalTime() / 24000);
                break;
            default:
                throw new IllegalStateException("Unknown query type: " + queryType);
        }
        src.sendMessage(t("commands.time.query", result));
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "query");
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandResult(org.spongepowered.api.command.CommandResult) CommandHelper.getWorld(org.lanternpowered.server.command.CommandHelper.getWorld) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) HashMap(java.util.HashMap) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandElement(org.spongepowered.api.command.args.CommandElement) GenericArguments(org.spongepowered.api.command.args.GenericArguments) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) Map(java.util.Map) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) CommandContext(org.spongepowered.api.command.args.CommandContext) HashMap(java.util.HashMap) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 2 with GenericArguments2

use of org.lanternpowered.server.command.element.GenericArguments2 in project LanternServer by LanternPowered.

the class CommandTitle method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.playerOrSource(Text.of("player"))).child(CommandSpec.builder().executor((src, args) -> {
        args.<Player>getOne("player").get().clearTitle();
        src.sendMessage(t("commands.title.success"));
        return CommandResult.success();
    }).build(), "clear").child(CommandSpec.builder().arguments(GenericArguments2.remainingString(Text.of("title"))).executor((src, args) -> {
        Text title;
        try {
            title = TextSerializers.JSON.deserialize(args.<String>getOne("title").get());
        } catch (TextParseException e) {
            throw new CommandException(t("commands.tellraw.jsonException", e.getMessage()));
        }
        args.<Player>getOne("player").get().sendTitle(Title.builder().title(title).build());
        src.sendMessage(t("commands.title.success"));
        return CommandResult.success();
    }).build(), "title").child(CommandSpec.builder().arguments(GenericArguments2.remainingString(Text.of("title"))).executor((src, args) -> {
        Text title;
        try {
            title = TextSerializers.JSON.deserialize(args.<String>getOne("title").get());
        } catch (TextParseException e) {
            throw new CommandException(t("commands.tellraw.jsonException", e.getMessage()));
        }
        args.<Player>getOne("player").get().sendTitle(Title.builder().subtitle(title).build());
        src.sendMessage(t("commands.title.success"));
        return CommandResult.success();
    }).build(), "subtitle").child(CommandSpec.builder().executor((src, args) -> {
        args.<Player>getOne("player").get().resetTitle();
        src.sendMessage(t("commands.title.success"));
        return CommandResult.success();
    }).build(), "reset").child(CommandSpec.builder().arguments(GenericArguments.integer(Text.of("fadeIn")), GenericArguments.integer(Text.of("stay")), GenericArguments.integer(Text.of("fadeOut"))).executor((src, args) -> {
        args.<Player>getOne("player").get().sendTitle(Title.builder().fadeIn(args.<Integer>getOne("fadeIn").get()).stay(args.<Integer>getOne("stay").get()).fadeOut(args.<Integer>getOne("fadeOut").get()).build());
        src.sendMessage(t("commands.title.success"));
        return CommandResult.success();
    }).build(), "times");
}
Also used : CommandException(org.spongepowered.api.command.CommandException) CommandResult(org.spongepowered.api.command.CommandResult) TextSerializers(org.spongepowered.api.text.serializer.TextSerializers) Text(org.spongepowered.api.text.Text) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) Title(org.spongepowered.api.text.title.Title) Player(org.spongepowered.api.entity.living.player.Player) TextParseException(org.spongepowered.api.text.serializer.TextParseException) GenericArguments(org.spongepowered.api.command.args.GenericArguments) PluginContainer(org.spongepowered.api.plugin.PluginContainer) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) Player(org.spongepowered.api.entity.living.player.Player) Text(org.spongepowered.api.text.Text) CommandException(org.spongepowered.api.command.CommandException) TextParseException(org.spongepowered.api.text.serializer.TextParseException)

Example 3 with GenericArguments2

use of org.lanternpowered.server.command.element.GenericArguments2 in project LanternServer by LanternPowered.

the class CommandParticle method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(new PatternMatchingCommandElement(Text.of("type")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            return Sponge.getGame().getRegistry().getAllOf(ParticleType.class).stream().filter(type -> ((LanternParticleType) type).getInternalType().isPresent()).map(CatalogType::getId).collect(Collectors.toList());
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<ParticleType> ret = Sponge.getGame().getRegistry().getType(ParticleType.class, choice);
            if (!ret.isPresent() || !((LanternParticleType) ret.get()).getInternalType().isPresent()) {
                throw new IllegalArgumentException("Invalid input " + choice + " was found");
            }
            return ret.get();
        }
    }, GenericArguments2.targetedVector3d(Text.of("position")), // The default value should be 0 for x, y and z
    GenericArguments2.vector3d(Text.of("offset"), Vector3d.ZERO), GenericArguments2.doubleNum(Text.of("speed"), 1.0), GenericArguments.optional(GenericArguments2.integer(Text.of("count"), 1)), GenericArguments.optional(new CommandElement(Text.of("mode")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            return args.next();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            Optional<String> arg = args.nextIfPresent();
            if (arg.isPresent()) {
                return Stream.of("normal", "force").filter(new StartsWithPredicate(arg.get())).collect(Collectors.toList());
            }
            return Collections.emptyList();
        }
    }), GenericArguments.optional(GenericArguments.player(Text.of("player"))), GenericArguments.optional(new CommandElement(Text.of("params")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            List<Integer> params = new ArrayList<>();
            while (args.hasNext()) {
                String arg = args.next();
                try {
                    params.add(Integer.parseInt(arg));
                } catch (NumberFormatException e) {
                    throw args.createError(t("Expected an integer, but input '%s' was not", arg));
                }
            }
            return params.stream().mapToInt(i -> i).toArray();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            return Collections.emptyList();
        }
    })).executor((src, args) -> {
        final LanternParticleType particleType = args.<LanternParticleType>getOne("type").get();
        final int particleId = particleType.getInternalType().getAsInt();
        final Vector3f position = args.<Vector3d>getOne("position").get().toFloat();
        final Vector3f offset = args.<Vector3d>getOne("offset").get().toFloat();
        final float speed = args.<Double>getOne("speed").get().floatValue();
        final int count = args.<Integer>getOne("count").orElse(1);
        final boolean longDistance = args.<String>getOne("mode").map(mode -> mode.equalsIgnoreCase("force")).orElse(false);
        final int[] params = args.<int[]>getOne("params").orElse(new int[0]);
        final LanternWorld world = CommandHelper.getWorld(src, args);
        final int dataLength;
        if (particleType == ParticleTypes.BLOCK_CRACK || particleType == ParticleTypes.BLOCK_DUST || particleType == ParticleTypes.FALLING_DUST) {
            dataLength = 1;
        } else if (particleType == ParticleTypes.ITEM_CRACK) {
            dataLength = 2;
        } else {
            dataLength = 0;
        }
        if (params.length != dataLength) {
            throw new CommandException(t("Invalid parameters (%s), length mismatch (got %s, expected %s) for the particle type %s", Arrays.toString(params), params.length, dataLength, particleType.getId()));
        }
        final MessagePlayOutSpawnParticle message = new MessagePlayOutSpawnParticle(particleId, position, offset, speed, count, params, longDistance);
        if (args.hasAny("player")) {
            args.<LanternPlayer>getOne("player").get().getConnection().send(message);
        } else {
            for (LanternPlayer player : world.getRawPlayers()) {
                player.getConnection().send(message);
            }
        }
        src.sendMessage(t("commands.particle.success", particleType.getName(), count));
        return CommandResult.success();
    });
}
Also used : Arrays(java.util.Arrays) MessagePlayOutSpawnParticle(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSpawnParticle) Vector3d(com.flowpowered.math.vector.Vector3d) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) GenericArguments(org.spongepowered.api.command.args.GenericArguments) ArrayList(java.util.ArrayList) ParticleType(org.spongepowered.api.effect.particle.ParticleType) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) ParticleTypes(org.spongepowered.api.effect.particle.ParticleTypes) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) LanternWorld(org.lanternpowered.server.world.LanternWorld) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) CommandResult(org.spongepowered.api.command.CommandResult) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) Stream(java.util.stream.Stream) Vector3f(com.flowpowered.math.vector.Vector3f) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer) Optional(java.util.Optional) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Collections(java.util.Collections) CommandContext(org.spongepowered.api.command.args.CommandContext) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) ParticleType(org.spongepowered.api.effect.particle.ParticleType) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) LanternWorld(org.lanternpowered.server.world.LanternWorld) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) ArrayList(java.util.ArrayList) List(java.util.List) CommandArgs(org.spongepowered.api.command.args.CommandArgs) Optional(java.util.Optional) MessagePlayOutSpawnParticle(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSpawnParticle) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) Vector3d(com.flowpowered.math.vector.Vector3d) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Vector3f(com.flowpowered.math.vector.Vector3f) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) CommandElement(org.spongepowered.api.command.args.CommandElement) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Nullable(javax.annotation.Nullable) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 4 with GenericArguments2

use of org.lanternpowered.server.command.element.GenericArguments2 in project LanternServer by LanternPowered.

the class CommandScoreboard method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none())).child(CommandSpec.builder().child(CommandSpec.builder().executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final Set<Objective> objectives = scoreboard.getObjectives();
        if (objectives.isEmpty()) {
            throw new CommandException(t("commands.scoreboard.objectives.list.empty"));
        }
        src.sendMessage(tb("commands.scoreboard.objectives.list.count", objectives.size()).color(TextColors.DARK_GREEN).build());
        objectives.forEach(objective -> src.sendMessage(t("commands.scoreboard.objectives.list.entry", objective.getName(), objective.getDisplayName(), objective.getCriterion().getName())));
        return CommandResult.success();
    }).build(), "list").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name")), GenericArguments.catalogedElement(Text.of("criterion"), Criterion.class), GenericArguments.flags().valueFlag(GenericArguments.catalogedElement(Text.of("display-mode"), ObjectiveDisplayMode.class), "-display-mode", "-dm", "d").buildWith(GenericArguments.none()), GenericArguments2.remainingString(Text.of("display-name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final String name = args.<String>getOne("name").get();
        final Criterion criterion = args.<Criterion>getOne("criterion").get();
        if (scoreboard.getObjective(name).isPresent()) {
            throw new CommandException(t("commands.scoreboard.objectives.add.alreadyExists", name));
        }
        if (name.length() > 16) {
            throw new CommandException(t("commands.scoreboard.objectives.add.tooLong", name, 16));
        }
        String displayName = args.<String>getOne("display-name").orElse(null);
        if (displayName != null && displayName.length() > 32) {
            throw new CommandException(t("commands.scoreboard.objectives.add.displayTooLong", displayName, 32));
        }
        Objective.Builder builder = Objective.builder().name(name).criterion(criterion);
        if (displayName != null && !displayName.isEmpty()) {
            builder.displayName(Text.of(displayName));
        }
        args.<ObjectiveDisplayMode>getOne("display-mode").ifPresent(builder::objectiveDisplayMode);
        scoreboard.addObjective(builder.build());
        src.sendMessage(t("commands.scoreboard.objectives.add.success", name));
        return CommandResult.success();
    }).build(), "add").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final String name = args.<String>getOne("name").get();
        scoreboard.removeObjective(scoreboard.getObjective(name).orElseThrow(() -> new CommandException(t("commands.scoreboard.objectiveNotFound", name))));
        src.sendMessage(t("commands.scoreboard.objectives.remove.success", name));
        return CommandResult.success();
    }).build(), "remove").child(CommandSpec.builder().arguments(GenericArguments.catalogedElement(Text.of("display-slot"), DisplaySlot.class), GenericArguments.optional(GenericArguments.string(Text.of("name")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final Optional<String> optName = args.<String>getOne("name");
        DisplaySlot displaySlot = args.<DisplaySlot>getOne("display-slot").get();
        Objective objective = null;
        if (optName.isPresent()) {
            final String name = optName.get();
            objective = scoreboard.getObjective(name).orElseThrow(() -> new CommandException(t("commands.scoreboard.objectiveNotFound", name)));
            src.sendMessage(t("commands.scoreboard.objectives.setdisplay.successSet", displaySlot.getName(), name));
        } else {
            src.sendMessage(t("commands.scoreboard.objectives.setdisplay.successCleared", displaySlot.getName()));
        }
        scoreboard.updateDisplaySlot(objective, displaySlot);
        return CommandResult.success();
    }).build(), "setdisplay").build(), "objectives").child(CommandSpec.builder().child(CommandSpec.builder().arguments(GenericArguments.optional(GenericArguments.string(Text.of("target")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        int result;
        if (args.hasAny("target")) {
            String entity = args.<String>getOne("target").get();
            Set<Score> scores = scoreboard.getScores(Text.of(entity));
            if (scores.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.players.list.player.empty"));
            }
            result = scores.size();
            src.sendMessage(tb("commands.scoreboard.players.list.player.count", result, entity).color(TextColors.DARK_GREEN).build());
            scores.forEach(score -> score.getObjectives().forEach(objective -> src.sendMessage(t("commands.scoreboard.players.list.player.entry", score.getScore(), objective.getDisplayName(), objective.getName()))));
        } else {
            Set<Text> names = scoreboard.getScores().stream().map(Score::getName).collect(Collectors.toSet());
            if (names.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.players.list.empty"));
            }
            result = names.size();
            src.sendMessage(tb("commands.scoreboard.players.list.count", result).color(TextColors.DARK_GREEN).build());
            src.sendMessage(Text.joinWith(Text.of(", "), names));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "list").child(createPlayerScoreSpec(Score::setScore), "set").child(createPlayerScoreSpec((score, value) -> score.setScore(score.getScore() + value)), "add").child(createPlayerScoreSpec((score, value) -> score.setScore(score.getScore() - value)), "remove").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("target")), GenericArguments.optional(GenericArguments.string(Text.of("objective")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String target = args.<String>getOne("target").get();
        if (args.hasAny("objective")) {
            String objectiveName = args.<String>getOne("objective").get();
            Objective objective = scoreboard.getObjective(objectiveName).orElseThrow(() -> new CommandException(t("commands.scoreboard.objectiveNotFound", objectiveName)));
            objective.removeScore(Text.of(target));
            src.sendMessage(t("commands.scoreboard.players.resetscore.success", objectiveName, target));
        } else {
            scoreboard.removeScores(Text.of(target));
            src.sendMessage(t("commands.scoreboard.players.reset.success", target));
        }
        return CommandResult.success();
    }).build(), "reset").build(), "players").child(CommandSpec.builder().child(CommandSpec.builder().arguments(GenericArguments.optional(GenericArguments.string(Text.of("name")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        int result;
        if (args.hasAny("name")) {
            String teamName = args.<String>getOne("name").get();
            Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
            Set<Text> members = team.getMembers();
            if (members.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.teams.list.player.empty", teamName));
            }
            result = members.size();
            src.sendMessage(tb("commands.scoreboard.teams.list.player.count", result, teamName).color(TextColors.DARK_GREEN).build());
            src.sendMessage(Text.joinWith(Text.of(", "), members));
        } else {
            Set<Team> teams = scoreboard.getTeams();
            if (teams.isEmpty()) {
                throw new CommandException(t("commands.scoreboard.teams.list.empty"));
            }
            result = teams.size();
            src.sendMessage(tb("commands.scoreboard.teams.list.count", result).color(TextColors.DARK_GREEN).build());
            teams.forEach(team -> src.sendMessage(t("commands.scoreboard.teams.list.entry", team.getName(), team.getDisplayName(), team.getMembers().size())));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "list").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name")), GenericArguments.optional(GenericArguments2.remainingString(Text.of("display-name")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        final String teamName = args.<String>getOne("name").get();
        if (scoreboard.getTeam(teamName).isPresent()) {
            throw new CommandException(t("commands.scoreboard.teams.add.alreadyExists", teamName));
        }
        if (teamName.length() > 16) {
            throw new CommandException(t("commands.scoreboard.teams.add.tooLong", teamName, 16));
        }
        String displayName = args.<String>getOne("display-name").orElse(null);
        if (displayName != null && displayName.length() > 32) {
            throw new CommandException(t("commands.scoreboard.teams.add.displayTooLong", displayName, 32));
        }
        Team.Builder teamBuilder = Team.builder().name(teamName);
        if (displayName != null && !displayName.isEmpty()) {
            teamBuilder.displayName(Text.of(displayName));
        }
        scoreboard.registerTeam(teamBuilder.build());
        src.sendMessage(t("commands.scoreboard.teams.add.success", teamName));
        return CommandResult.success();
    }).build(), "add").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").get();
        final Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
        team.unregister();
        src.sendMessage(t("commands.scoreboard.teams.remove.success", teamName));
        return CommandResult.success();
    }).build(), "remove").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name"))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").get();
        final Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
        Set<Text> members = team.getMembers();
        if (members.isEmpty()) {
            throw new CommandException(t("commands.scoreboard.teams.empty.alreadyEmpty", teamName));
        }
        int result = members.size();
        ((LanternTeam) team).removeMembers(members);
        src.sendMessage(t("commands.scoreboard.teams.empty.success", result, teamName));
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "empty").child(CommandSpec.builder().arguments(GenericArguments.optional(GenericArguments.string(Text.of("name"))), GenericArguments.optional(GenericArguments2.remainingStringArray(Text.of("players")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").orElse(null);
        final Team team = teamName == null ? null : scoreboard.getTeam(teamName).orElse(null);
        Set<Text> members = args.<String[]>getOne("players").map(array -> Arrays.stream(array).map(LanternTexts::fromLegacy).collect(Collectors.toSet())).orElse(new HashSet<>());
        // that wants to leave a team
        if (teamName != null && team == null) {
            members.add(LanternTexts.fromLegacy(teamName));
        }
        // If there are no members found, use the source if possible
        if (members.isEmpty() && src instanceof Player) {
            members.add(((Player) src).getTeamRepresentation());
        }
        // If there is a team specified, remove the members from a specific team
        Collection<Team> teams = team == null ? scoreboard.getTeams() : Collections.singleton(team);
        List<Text> failedMembers = null;
        for (Team team0 : teams) {
            List<Text> failedMembers0 = ((LanternTeam) team0).removeMembers(members);
            if (failedMembers == null) {
                failedMembers = failedMembers0;
            } else {
                failedMembers.retainAll(failedMembers0);
            }
        }
        if (failedMembers != null) {
            members.removeAll(failedMembers);
        }
        int result = members.size();
        if (result > 0) {
            src.sendMessage(t("commands.scoreboard.teams.leave.success", result, Text.joinWith(Text.of(", "), members)));
        }
        if (failedMembers != null && failedMembers.size() > 0) {
            src.sendMessage(error(t("commands.scoreboard.teams.leave.failure", failedMembers.size(), Text.joinWith(Text.of(", "), failedMembers))));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "leave").child(CommandSpec.builder().arguments(GenericArguments.string(Text.of("name")), GenericArguments.optional(GenericArguments2.remainingStringArray(Text.of("players")))).executor((src, args) -> {
        // Get the scoreboard of the world the command source is located in
        final Scoreboard scoreboard = CommandHelper.getWorld(src, args).getScoreboard();
        String teamName = args.<String>getOne("name").get();
        final Team team = scoreboard.getTeam(teamName).orElseThrow(() -> new CommandException(t("commands.scoreboard.teamNotFound", teamName)));
        Set<Text> members = args.<String[]>getOne("players").map(array -> Arrays.stream(array).map(LanternTexts::fromLegacy).collect(Collectors.toSet())).orElse(new HashSet<>());
        // If there are no members found, use the source if possible
        if (members.isEmpty() && src instanceof Player) {
            members.add(((Player) src).getTeamRepresentation());
        }
        List<Text> failedMembers = ((LanternTeam) team).addMembers(members);
        int result = members.size();
        if (result > 0) {
            src.sendMessage(t("commands.scoreboard.teams.join.success", result, teamName, Text.joinWith(Text.of(", "), members)));
        }
        if (failedMembers.size() > 0) {
            src.sendMessage(error(t("commands.scoreboard.teams.join.failure", failedMembers.size(), teamName, Text.joinWith(Text.of(", "), failedMembers))));
        }
        return CommandResult.builder().successCount(1).queryResult(result).build();
    }).build(), "join").build(), "teams");
}
Also used : Arrays(java.util.Arrays) LanternTexts(org.lanternpowered.server.text.LanternTexts) GenericArguments(org.spongepowered.api.command.args.GenericArguments) HashSet(java.util.HashSet) ObjectiveDisplayMode(org.spongepowered.api.scoreboard.objective.displaymode.ObjectiveDisplayMode) TranslationHelper.tb(org.lanternpowered.server.text.translation.TranslationHelper.tb) Text(org.spongepowered.api.text.Text) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) BiConsumer(java.util.function.BiConsumer) Objective(org.spongepowered.api.scoreboard.objective.Objective) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) CommandResult(org.spongepowered.api.command.CommandResult) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) Collection(java.util.Collection) Set(java.util.Set) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) Collectors(java.util.stream.Collectors) DisplaySlot(org.spongepowered.api.scoreboard.displayslot.DisplaySlot) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) List(java.util.List) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) Collections(java.util.Collections) CommandMessageFormatting.error(org.spongepowered.api.command.CommandMessageFormatting.error) HashSet(java.util.HashSet) Set(java.util.Set) Scoreboard(org.spongepowered.api.scoreboard.Scoreboard) Criterion(org.spongepowered.api.scoreboard.critieria.Criterion) DisplaySlot(org.spongepowered.api.scoreboard.displayslot.DisplaySlot) Team(org.spongepowered.api.scoreboard.Team) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) List(java.util.List) LanternTeam(org.lanternpowered.server.scoreboard.LanternTeam) HashSet(java.util.HashSet) Player(org.spongepowered.api.entity.living.player.Player) Text(org.spongepowered.api.text.Text) CommandException(org.spongepowered.api.command.CommandException) Objective(org.spongepowered.api.scoreboard.objective.Objective) Score(org.spongepowered.api.scoreboard.Score) LanternScore(org.lanternpowered.server.scoreboard.LanternScore) LanternTexts(org.lanternpowered.server.text.LanternTexts) Collection(java.util.Collection)

Example 5 with GenericArguments2

use of org.lanternpowered.server.command.element.GenericArguments2 in project LanternServer by LanternPowered.

the class CommandTp method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.optional(GenericArguments.player(Text.of("target"))), GenericArguments.firstParsing(GenericArguments.player(Text.of("destination")), GenericArguments.seq(/*
                                        GenericArguments.flags()
                                                .valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY),
                                                        "-world", "w")
                                                .buildWith(GenericArguments.none()),
                                        */
    GenericArguments.optional(GenericArguments.world(CommandHelper.WORLD_KEY)), GenericArguments2.targetedRelativeVector3d(Text.of("coordinates")), GenericArguments.optional(GenericArguments.seq(GenericArguments2.relativeDoubleNum(Text.of("y-rot")), GenericArguments2.relativeDoubleNum(Text.of("x-rot"))))))).executor((src, args) -> {
        Player target = args.<Player>getOne("target").orElse(null);
        if (target == null) {
            if (!(src instanceof Player)) {
                throw new CommandException(t("The target parameter is only optional for players."));
            }
            target = (Player) src;
        }
        final Optional<Player> optDestination = args.getOne("destination");
        if (optDestination.isPresent()) {
            final Player destination = optDestination.get();
            target.setTransform(destination.getTransform());
            src.sendMessage(t("commands.tp.success", target.getName(), destination.getName()));
        } else {
            final RelativeVector3d coords = args.<RelativeVector3d>getOne("coordinates").get();
            final Transform<World> transform = target.getTransform();
            World world = args.<WorldProperties>getOne(CommandHelper.WORLD_KEY).flatMap(p -> Lantern.getServer().getWorld(p.getUniqueId())).orElse(transform.getExtent());
            Vector3d position = coords.applyToValue(transform.getPosition());
            final Optional<RelativeDouble> optYRot = args.getOne("y-rot");
            if (optYRot.isPresent()) {
                final Vector3d rot = transform.getRotation();
                double xRot = args.<RelativeDouble>getOne("x-rot").get().applyToValue(rot.getX());
                double yRot = args.<RelativeDouble>getOne("y-rot").get().applyToValue(rot.getY());
                double zRot = rot.getZ();
                target.setLocationAndRotation(new Location<>(world, position), new Vector3d(xRot, yRot, zRot));
            } else {
                target.setLocation(new Location<>(world, position));
            }
            src.sendMessage(t("commands.tp.success.position", target.getName(), formatDouble(position.getX()), formatDouble(position.getY()), formatDouble(position.getZ()), world.getName()));
        }
        return CommandResult.success();
    });
}
Also used : CommandResult(org.spongepowered.api.command.CommandResult) RelativeDouble(org.lanternpowered.server.command.element.RelativeDouble) Location(org.spongepowered.api.world.Location) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) Vector3d(com.flowpowered.math.vector.Vector3d) GenericArguments(org.spongepowered.api.command.args.GenericArguments) RelativeVector3d(org.lanternpowered.server.command.element.RelativeVector3d) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) Text(org.spongepowered.api.text.Text) Lantern(org.lanternpowered.server.game.Lantern) Transform(org.spongepowered.api.entity.Transform) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) World(org.spongepowered.api.world.World) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) Optional(java.util.Optional) Player(org.spongepowered.api.entity.living.player.Player) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Player(org.spongepowered.api.entity.living.player.Player) RelativeVector3d(org.lanternpowered.server.command.element.RelativeVector3d) CommandException(org.spongepowered.api.command.CommandException) World(org.spongepowered.api.world.World) Vector3d(com.flowpowered.math.vector.Vector3d) RelativeVector3d(org.lanternpowered.server.command.element.RelativeVector3d) RelativeDouble(org.lanternpowered.server.command.element.RelativeDouble) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Aggregations

GenericArguments2 (org.lanternpowered.server.command.element.GenericArguments2)6 TranslationHelper.t (org.lanternpowered.server.text.translation.TranslationHelper.t)6 CommandResult (org.spongepowered.api.command.CommandResult)6 GenericArguments (org.spongepowered.api.command.args.GenericArguments)6 CommandSpec (org.spongepowered.api.command.spec.CommandSpec)6 PluginContainer (org.spongepowered.api.plugin.PluginContainer)6 Text (org.spongepowered.api.text.Text)6 CommandException (org.spongepowered.api.command.CommandException)5 List (java.util.List)4 Optional (java.util.Optional)4 Player (org.spongepowered.api.entity.living.player.Player)4 Collectors (java.util.stream.Collectors)3 Vector3d (com.flowpowered.math.vector.Vector3d)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 Nullable (javax.annotation.Nullable)2 LanternPlayer (org.lanternpowered.server.entity.living.player.LanternPlayer)2 Lantern (org.lanternpowered.server.game.Lantern)2 Sponge (org.spongepowered.api.Sponge)2 CommandSource (org.spongepowered.api.command.CommandSource)2