Search in sources :

Example 26 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project LanternServer by LanternPowered.

the class TestInventoryPlugin method onInit.

@Listener
public void onInit(GameInitializationEvent event) {
    this.myArchetype = InventoryArchetype.builder().with(InventoryArchetypes.MENU_ROW).title(Text.of("My Fancy Title")).property(InventoryDimension.of(9, 1)).property(new GuiIdProperty(GuiIds.CHEST)).build("inventory_test:test", "Test Inventory");
    Sponge.getCommandManager().register(this, CommandSpec.builder().executor((src, args) -> {
        if (!(src instanceof Player)) {
            throw new CommandException(t("Only players may use this command."));
        }
        final Inventory inventory = Inventory.builder().of(this.myArchetype).withCarrier((Carrier) src).build(this);
        System.out.println(inventory.getClass().getName());
        final ItemStack itemStack = ItemStack.of(ItemTypes.LOG, 64);
        itemStack.offer(Keys.TREE_TYPE, TreeTypes.JUNGLE);
        inventory.offer(itemStack);
        ((Player) src).openInventory(inventory);
        return CommandResult.success();
    }).build(), "test-a-inv");
    Keys.COAL_TYPE.registerEvent(ItemStack.class, event1 -> {
        final DataTransactionResult result = event1.getEndResult();
        final List<ImmutableValue<?>> newSuccessfulData = new ArrayList<>(result.getSuccessfulData());
        Iterator<ImmutableValue<?>> it = newSuccessfulData.iterator();
        while (it.hasNext()) {
            final ImmutableValue<?> value = it.next();
            if (value.getKey() == Keys.COAL_TYPE) {
                System.out.println("Changed coal type to: " + ((CoalType) value.get()).getId() + ", but this not allowed");
                it.remove();
                break;
            }
        }
        final List<ImmutableValue<?>> newReplacedData = new ArrayList<>(result.getReplacedData());
        it = newSuccessfulData.iterator();
        while (it.hasNext()) {
            final ImmutableValue<?> value = it.next();
            if (value.getKey() == Keys.COAL_TYPE) {
                it.remove();
                break;
            }
        }
        event1.proposeChanges(DataTransactionResult.builder().result(result.getType()).reject(result.getRejectedData()).replace(newReplacedData).success(newSuccessfulData).build());
    });
}
Also used : GuiIdProperty(org.spongepowered.api.item.inventory.property.GuiIdProperty) Player(org.spongepowered.api.entity.living.player.Player) ImmutableValue(org.spongepowered.api.data.value.immutable.ImmutableValue) ArrayList(java.util.ArrayList) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult) CommandException(org.spongepowered.api.command.CommandException) Carrier(org.spongepowered.api.item.inventory.Carrier) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Inventory(org.spongepowered.api.item.inventory.Inventory) Listener(org.spongepowered.api.event.Listener)

Example 27 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project LanternServer by LanternPowered.

the class LanternEventManager method post.

@SuppressWarnings({ "unchecked", "ConstantConditions" })
@Override
public boolean post(Event event) {
    checkNotNull(event, "event");
    final Class<? extends Event> eventClass = event.getClass();
    final EventType<? extends Event> eventType;
    if (event instanceof GenericEvent) {
        eventType = new EventType(eventClass, checkNotNull(((GenericEvent) event).getGenericType()));
    } else {
        eventType = new EventType(eventClass, null);
    }
    final List<RegisteredListener<?>> listeners = this.listenersCache.get(eventType);
    // Special case
    if (event instanceof AbstractValueChangeEvent) {
        final AbstractValueChangeEvent event1 = (AbstractValueChangeEvent) event;
        final TempDataEventData temp = new TempDataEventData();
        temp.lastResult = event1.getEndResult();
        return post(event, listeners, listener -> {
            if (listener.getHandler() instanceof KeyEventListener) {
                final KeyEventListener keyEventListener = (KeyEventListener) listener.getHandler();
                if (keyEventListener.getDataHolderPredicate().test(event1.getTargetHolder())) {
                    final DataTransactionResult newResult = event1.getEndResult();
                    // We need the keys, only regenerate if changed
                    if (temp.keys == null || temp.lastResult != newResult) {
                        // Ignore rejected data, nothing changed for those keys
                        if (temp.baseKeys == null) {
                            temp.baseKeys = new HashSet<>();
                            final DataTransactionResult original = event1.getOriginalChanges();
                            original.getSuccessfulData().forEach(value -> temp.baseKeys.add(value.getKey()));
                            original.getReplacedData().forEach(value -> temp.baseKeys.add(value.getKey()));
                        }
                        if (event1.getOriginalChanges() == newResult) {
                            temp.keys = temp.baseKeys;
                        } else {
                            temp.keys = new HashSet<>();
                            temp.keys.addAll(temp.baseKeys);
                            newResult.getSuccessfulData().forEach(value -> temp.keys.add(value.getKey()));
                            newResult.getReplacedData().forEach(value -> temp.keys.add(value.getKey()));
                        }
                    }
                    if (temp.keys.contains(keyEventListener.getKey())) {
                        listener.handle(event);
                    }
                }
            }
        });
    }
    return post(event, listeners);
}
Also used : GenericEvent(org.spongepowered.api.event.GenericEvent) AbstractValueChangeEvent(org.spongepowered.api.event.impl.AbstractValueChangeEvent) KeyEventListener(org.lanternpowered.server.data.key.KeyEventListener) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult)

Example 28 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult 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 29 with DataTransactionResult

use of org.spongepowered.api.data.DataTransactionResult in project Nucleus by NucleusPowered.

the class SetExperience method executeCommand.

@Override
public CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    Player pl = this.getUserFromArgs(Player.class, src, ExperienceCommand.playerKey, args);
    if (!ExperienceCommand.checkGameMode(pl, src)) {
        return CommandResult.empty();
    }
    Optional<Integer> l = args.getOne(ExperienceCommand.levelKey);
    DataTransactionResult dtr;
    dtr = l.map(integer -> pl.offer(Keys.EXPERIENCE_LEVEL, integer)).orElseGet(() -> pl.offer(Keys.TOTAL_EXPERIENCE, args.<Integer>getOne(ExperienceCommand.experienceKey).get()));
    return ExperienceCommand.tellUserAboutExperience(src, pl, dtr.isSuccessful());
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) DataTransactionResult(org.spongepowered.api.data.DataTransactionResult)

Aggregations

DataTransactionResult (org.spongepowered.api.data.DataTransactionResult)29 ItemStack (org.spongepowered.api.item.inventory.ItemStack)6 DataHolder (org.spongepowered.api.data.DataHolder)4 ImmutableValue (org.spongepowered.api.data.value.immutable.ImmutableValue)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 BlockState (org.spongepowered.api.block.BlockState)3 BaseValue (org.spongepowered.api.data.value.BaseValue)3 Player (org.spongepowered.api.entity.living.player.Player)3 IMixinCustomDataHolder (org.spongepowered.common.interfaces.data.IMixinCustomDataHolder)3 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 Optional (java.util.Optional)2 Set (java.util.Set)2 EnumFacing (net.minecraft.util.EnumFacing)2 Sponge (org.spongepowered.api.Sponge)2 TileEntity (org.spongepowered.api.block.tileentity.TileEntity)2 DataView (org.spongepowered.api.data.DataView)2