Search in sources :

Example 16 with GameMode

use of org.spongepowered.api.entity.living.player.gamemode.GameMode in project LanternServer by LanternPowered.

the class CommandGameMode method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final ImmutableMap.Builder<String, Object> baseBuilder = ImmutableMap.builder();
    final ImmutableMap.Builder<String, Object> aliasesBuilder = ImmutableMap.builder();
    for (GameMode gameMode : Sponge.getRegistry().getAllOf(GameMode.class)) {
        // Ignore the not set game mode
        if (gameMode == GameModes.NOT_SET) {
            continue;
        }
        baseBuilder.put(gameMode.getName(), gameMode);
        aliasesBuilder.put(((LanternGameMode) gameMode).getInternalId() + "", gameMode);
    }
    aliasesBuilder.put("s", GameModes.SURVIVAL);
    aliasesBuilder.put("c", GameModes.CREATIVE);
    aliasesBuilder.put("a", GameModes.ADVENTURE);
    aliasesBuilder.put("sp", GameModes.SPECTATOR);
    specBuilder.arguments(ChoicesElement.of(Text.of("game-mode"), baseBuilder.build(), aliasesBuilder.build(), false, true), GenericArguments.playerOrSource(Text.of("player"))).executor((src, args) -> {
        final GameMode gameMode = args.<GameMode>getOne("game-mode").get();
        final Player player = args.<Player>getOne("player").get();
        player.offer(Keys.GAME_MODE, gameMode);
        final Text gameModeText = Text.of(gameMode.getTranslation());
        if (player == src) {
            src.sendMessage(t("commands.gamemode.success.self", gameModeText));
        } else {
            if (((RuleHolder) player.getWorld()).getOrCreateRule(RuleTypes.SEND_COMMAND_FEEDBACK).getValue()) {
                player.sendMessage(t("gameMode.changed", gameModeText));
            }
            src.sendMessage(t("commands.gamemode.success.other", player.getName(), gameModeText));
        }
        return CommandResult.success();
    });
}
Also used : LanternGameMode(org.lanternpowered.server.entity.living.player.gamemode.LanternGameMode) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) Player(org.spongepowered.api.entity.living.player.Player) LanternGameMode(org.lanternpowered.server.entity.living.player.gamemode.LanternGameMode) Text(org.spongepowered.api.text.Text) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 17 with GameMode

use of org.spongepowered.api.entity.living.player.gamemode.GameMode in project LanternServer by LanternPowered.

the class PlayerEntityProtocol method update.

@Override
protected void update(EntityProtocolUpdateContext context) {
    final GameMode gameMode = this.entity.get(Keys.GAME_MODE).get();
    final boolean canFly = canFly();
    final float flySpeed = getFlySpeed();
    final float fieldOfView = getFovModifier();
    if (gameMode != this.lastGameMode) {
        context.sendToSelf(() -> new MessagePlayOutSetGameMode((LanternGameMode) gameMode));
        context.sendToSelf(() -> new MessagePlayOutPlayerAbilities(this.entity.get(Keys.IS_FLYING).orElse(false), canFly, false, gameMode == GameModes.CREATIVE, flySpeed, fieldOfView));
        this.lastGameMode = gameMode;
        this.lastCanFly = canFly;
        this.lastFlySpeed = flySpeed;
        this.lastFieldOfView = fieldOfView;
    } else if (canFly != this.lastCanFly || flySpeed != this.lastFlySpeed || fieldOfView != this.lastFieldOfView) {
        context.sendToSelf(() -> new MessagePlayOutPlayerAbilities(this.entity.get(Keys.IS_FLYING).orElse(false), canFly, false, gameMode == GameModes.CREATIVE, flySpeed, fieldOfView));
        this.lastCanFly = canFly;
        this.lastFlySpeed = flySpeed;
        this.lastFieldOfView = fieldOfView;
    }
    final float health = this.entity.get(Keys.HEALTH).get().floatValue();
    final int foodLevel = this.entity.get(Keys.FOOD_LEVEL).get();
    final float saturation = this.entity.get(Keys.SATURATION).get().floatValue();
    if (health != this.lastHealth || foodLevel != this.lastFoodLevel || saturation == 0.0f != this.lastHungry) {
        context.sendToSelf(() -> new MessagePlayOutPlayerHealthUpdate(health, foodLevel, saturation));
        this.lastHealth = health;
        this.lastFoodLevel = foodLevel;
        this.lastHungry = saturation == 0.0f;
    }
    super.update(context);
    final TopHat topHat = getTopHat();
    if (topHat != this.lastTopHat) {
        if (this.lastTopHat == null) {
            sendPassengerStack(context);
            sendHat(context, topHat);
        } else if (topHat == null) {
            removePassengerStack(context);
        } else {
            sendHat(context, topHat);
        }
        this.lastTopHat = topHat;
    }
    if (this.lastYaw0 != this.lastYaw || this.lastPitch0 != this.lastPitch || this.lastFlags0 != this.lastFlags) {
        for (final int id : this.passengerStack) {
            context.sendToSelf(() -> new MessagePlayOutEntityLook(id, this.lastYaw, this.lastPitch, this.entity.isOnGround()));
        }
        if (this.lastTopHat != null) {
            context.sendToSelf(() -> new MessagePlayOutEntityHeadLook(this.passengerStack[10], this.lastYaw));
            context.sendToSelf(() -> new MessagePlayOutEntityHeadLook(this.passengerStack[11], this.lastYaw));
            context.sendToSelf(() -> new MessagePlayOutEntityHeadLook(this.passengerStack[12], this.lastYaw));
            // context.sendToSelf(() -> new MessagePlayOutEntityHeadLook(this.passengerStack[14], this.lastYaw));
            if (this.lastFlags0 != this.lastFlags) {
                final boolean glow = (this.lastFlags & 0x40) != 0;
                final ParameterList parameterList = new ByteBufParameterList(ByteBufferAllocator.unpooled());
                parameterList.add(EntityParameters.Base.FLAGS, (byte) (0x20 | (glow ? 0x40 : 0x00)));
                context.sendToAll(() -> new MessagePlayOutEntityMetadata(this.passengerStack[10], parameterList));
                context.sendToAll(() -> new MessagePlayOutEntityMetadata(this.passengerStack[11], parameterList));
            }
        }
        this.lastYaw0 = this.lastYaw;
        this.lastPitch0 = this.lastPitch;
        this.lastFlags0 = this.lastFlags;
    }
    // Some 1.11.2 magic, ultra secret stuff...
    final boolean elytraFlying = this.entity.get(LanternKeys.IS_ELYTRA_FLYING).orElse(false);
    final boolean elytraSpeedBoost = this.entity.get(LanternKeys.ELYTRA_SPEED_BOOST).orElse(false);
    if (this.lastElytraFlying != elytraFlying || this.lastElytraSpeedBoost != elytraSpeedBoost) {
        if (this.lastElytraFlying && this.lastElytraSpeedBoost) {
            context.sendToAll(() -> new MessagePlayOutDestroyEntities(this.elytraRocketId));
        } else if (elytraFlying && elytraSpeedBoost) {
            // Create the fireworks data item
            final LanternItemStack itemStack = new LanternItemStack(ItemTypes.FIREWORKS);
            // Write the item to a parameter list
            final ByteBufParameterList parameterList = new ByteBufParameterList(ByteBufferAllocator.unpooled());
            parameterList.add(EntityParameters.Fireworks.ITEM, itemStack);
            parameterList.add(EntityParameters.Fireworks.ELYTRA_BOOST_PLAYER, getRootEntityId());
            context.sendToAll(() -> new MessagePlayOutSpawnObject(this.elytraRocketId, UUID.randomUUID(), 76, 0, this.entity.getPosition(), 0, 0, Vector3d.ZERO));
            context.sendToAll(() -> new MessagePlayOutEntityMetadata(this.elytraRocketId, parameterList));
        }
        this.lastElytraSpeedBoost = elytraSpeedBoost;
        this.lastElytraFlying = elytraFlying;
    }
}
Also used : TopHat(org.lanternpowered.server.extra.accessory.TopHat) ByteBufParameterList(org.lanternpowered.server.network.entity.parameter.ByteBufParameterList) LanternGameMode(org.lanternpowered.server.entity.living.player.gamemode.LanternGameMode) MessagePlayOutSpawnObject(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSpawnObject) LanternItemStack(org.lanternpowered.server.inventory.LanternItemStack) MessagePlayOutSetGameMode(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSetGameMode) LanternGameMode(org.lanternpowered.server.entity.living.player.gamemode.LanternGameMode) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) MessagePlayOutPlayerHealthUpdate(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutPlayerHealthUpdate) MessagePlayOutEntityLook(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutEntityLook) MessagePlayOutSetGameMode(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSetGameMode) MessagePlayOutDestroyEntities(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutDestroyEntities) ParameterList(org.lanternpowered.server.network.entity.parameter.ParameterList) ByteBufParameterList(org.lanternpowered.server.network.entity.parameter.ByteBufParameterList) MessagePlayOutEntityMetadata(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutEntityMetadata) MessagePlayOutPlayerAbilities(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutPlayerAbilities) MessagePlayOutEntityHeadLook(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutEntityHeadLook)

Example 18 with GameMode

use of org.spongepowered.api.entity.living.player.gamemode.GameMode in project Nucleus by NucleusPowered.

the class ImprovedGameModeArgument method parseValue.

@Nullable
@Override
protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
    String arg = args.next();
    GameMode mode = gameModeMap.get(arg.toLowerCase());
    if (mode == null) {
        throw args.createError(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("args.gamemode.error", arg));
    }
    return mode;
}
Also used : GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) Nullable(javax.annotation.Nullable)

Example 19 with GameMode

use of org.spongepowered.api.entity.living.player.gamemode.GameMode in project Nucleus by NucleusPowered.

the class KillCommand method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    Collection<Entity> entities = args.getAll(key);
    int entityKillCount = 0;
    int playerKillCount = 0;
    for (Entity x : entities) {
        if (x instanceof Player) {
            Player pl = (Player) x;
            GameMode gm = pl.gameMode().getDirect().orElseGet(() -> pl.gameMode().getDefault());
            if (gm != GameModes.SURVIVAL && gm != GameModes.NOT_SET) {
                if (entities.size() == 1) {
                    throw ReturnMessageException.fromKey("command.kill.wronggm", pl.getName());
                } else {
                    continue;
                }
            }
        }
        DataTransactionResult dtr = x.offer(Keys.HEALTH, 0d);
        if (!dtr.isSuccessful() && !(x instanceof Living)) {
            x.remove();
        }
        entityKillCount++;
        if (x instanceof Player) {
            playerKillCount++;
            src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.kill.killed", Nucleus.getNucleus().getNameUtil().getSerialisedName((Player) x)));
            ((Player) x).sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.kill.killedby", src.getName()));
        }
    }
    if (entityKillCount > playerKillCount) {
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.kill.overall", String.valueOf(entityKillCount), String.valueOf(playerKillCount)));
    }
    return CommandResult.success();
}
Also used : Entity(org.spongepowered.api.entity.Entity) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) Player(org.spongepowered.api.entity.living.player.Player) Living(org.spongepowered.api.entity.living.Living) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult)

Example 20 with GameMode

use of org.spongepowered.api.entity.living.player.gamemode.GameMode in project Nucleus by NucleusPowered.

the class CreateWorldCommand method executeCommand.

@Override
public CommandResult executeCommand(final CommandSource src, CommandContext args) throws Exception {
    String nameInput = args.<String>getOne(name).get();
    Optional<DimensionType> dimensionInput = args.getOne(dimension);
    Optional<GeneratorType> generatorInput = args.getOne(generator);
    Optional<GameMode> gamemodeInput = args.getOne(gamemode);
    Optional<Difficulty> difficultyInput = args.getOne(difficulty);
    Collection<WorldGeneratorModifier> modifiers = args.getAll(modifier);
    Optional<Long> seedInput = args.getOne(seed);
    boolean genStructures = !args.hasAny("n");
    boolean loadOnStartup = !args.hasAny("l") || args.<Boolean>getOne("l").orElse(true);
    boolean keepSpawnLoaded = !args.hasAny("k") || args.<Boolean>getOne("k").orElse(true);
    boolean allowCommands = !args.hasAny("c") || args.<Boolean>getOne("c").orElse(true);
    boolean bonusChest = !args.hasAny("b") || args.<Boolean>getOne("b").orElse(true);
    if (Sponge.getServer().getAllWorldProperties().stream().anyMatch(x -> x.getWorldName().equalsIgnoreCase(nameInput))) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.world.create.exists", nameInput));
    }
    // Does the world exist?
    Path worldPath = Sponge.getGame().getGameDirectory().resolve("world");
    Path worldDir = worldPath.resolve(nameInput);
    if (!args.hasAny("i") && Files.exists(worldDir)) {
        throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.world.import.noexist", nameInput));
    }
    if (args.hasAny("i") && Files.exists(worldDir)) {
        onImport(worldDir, nameInput);
    }
    WorldArchetype.Builder worldSettingsBuilder = WorldArchetype.builder().enabled(true);
    if (args.hasAny(preset)) {
        WorldArchetype preset1 = args.<WorldArchetype>getOne(preset).get();
        worldSettingsBuilder.from(preset1);
        dimensionInput.ifPresent(worldSettingsBuilder::dimension);
        generatorInput.ifPresent(worldSettingsBuilder::generator);
        gamemodeInput.ifPresent(worldSettingsBuilder::gameMode);
        difficultyInput.ifPresent(worldSettingsBuilder::difficulty);
        if (!modifiers.isEmpty()) {
            modifiers.addAll(preset1.getGeneratorModifiers());
            worldSettingsBuilder.generatorModifiers(modifiers.toArray(new WorldGeneratorModifier[modifiers.size()]));
        }
    } else {
        worldSettingsBuilder.dimension(dimensionInput.orElse(DimensionTypes.OVERWORLD)).generator(generatorInput.orElse(GeneratorTypes.DEFAULT)).gameMode(gamemodeInput.orElse(GameModes.SURVIVAL)).difficulty(difficultyInput.orElse(Difficulties.NORMAL));
        if (!modifiers.isEmpty()) {
            worldSettingsBuilder.generatorModifiers(modifiers.toArray(new WorldGeneratorModifier[modifiers.size()]));
        }
    }
    worldSettingsBuilder.loadsOnStartup(loadOnStartup).keepsSpawnLoaded(keepSpawnLoaded).usesMapFeatures(genStructures).commandsAllowed(allowCommands).generateBonusChest(bonusChest);
    seedInput.ifPresent(worldSettingsBuilder::seed);
    WorldArchetype wa = worldSettingsBuilder.build(nameInput.toLowerCase(), nameInput);
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.world.create.begin", nameInput));
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.world.create.newparams", wa.getDimensionType().getName(), wa.getGeneratorType().getName(), modifierString(modifiers), wa.getGameMode().getName(), wa.getDifficulty().getName()));
    src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.world.create.newparams2", String.valueOf(loadOnStartup), String.valueOf(keepSpawnLoaded), String.valueOf(genStructures), String.valueOf(allowCommands), String.valueOf(bonusChest)));
    WorldProperties worldProperties = Sponge.getGame().getServer().createWorldProperties(nameInput, wa);
    if (this.worldBorderDefault != null && this.worldBorderDefault > 0) {
        worldProperties.setWorldBorderDiameter(this.worldBorderDefault);
    }
    worldProperties.setDifficulty(wa.getDifficulty());
    if (!Sponge.getServer().saveWorldProperties(worldProperties)) {
        throw ReturnMessageException.fromKey("command.world.create.couldnotsave", nameInput);
    }
    Optional<World> world = Sponge.getGame().getServer().loadWorld(worldProperties);
    if (world.isPresent()) {
        world.get().getProperties().setDifficulty(wa.getDifficulty());
        src.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.world.create.success", nameInput));
        return CommandResult.success();
    } else {
        throw ReturnMessageException.fromKey("command.world.create.worldfailedtoload", nameInput);
    }
}
Also used : Path(java.nio.file.Path) DimensionType(org.spongepowered.api.world.DimensionType) Difficulty(org.spongepowered.api.world.difficulty.Difficulty) ReturnMessageException(io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException) World(org.spongepowered.api.world.World) GeneratorType(org.spongepowered.api.world.GeneratorType) GameMode(org.spongepowered.api.entity.living.player.gamemode.GameMode) WorldGeneratorModifier(org.spongepowered.api.world.gen.WorldGeneratorModifier) WorldArchetype(org.spongepowered.api.world.WorldArchetype) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Aggregations

GameMode (org.spongepowered.api.entity.living.player.gamemode.GameMode)23 Player (org.spongepowered.api.entity.living.player.Player)5 Optional (java.util.Optional)4 LanternGameMode (org.lanternpowered.server.entity.living.player.gamemode.LanternGameMode)4 Entity (org.spongepowered.api.entity.Entity)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 LanternItemStack (org.lanternpowered.server.inventory.LanternItemStack)3 ItemStack (org.spongepowered.api.item.inventory.ItemStack)3 WorldProperties (org.spongepowered.api.world.storage.WorldProperties)3 Vector3d (com.flowpowered.math.vector.Vector3d)2 ReturnMessageException (io.github.nucleuspowered.nucleus.internal.command.ReturnMessageException)2 Instant (java.time.Instant)2 HashMap (java.util.HashMap)2 UUID (java.util.UUID)2 Collectors (java.util.stream.Collectors)2 Nullable (javax.annotation.Nullable)2 CauseStack (org.lanternpowered.server.event.CauseStack)2 Keys (org.spongepowered.api.data.key.Keys)2 GameModes (org.spongepowered.api.entity.living.player.gamemode.GameModes)2