use of org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult in project Skree by Skelril.
the class MarketImplUtil method giveItems.
public static Clause<Boolean, List<Clause<ItemStack, Integer>>> giveItems(Player player, Collection<ItemStack> stacks, Cause cause) {
List<Clause<ItemStack, Integer>> transactions = new ArrayList<>(stacks.size());
List<ItemStackSnapshot> itemBuffer = new ArrayList<>();
itemBuffer.addAll(stacks.stream().map(ItemStack::createSnapshot).collect(Collectors.toList()));
PlayerInventory playerInventory = player.getInventory().query(PlayerInventory.class);
List<Inventory> inventories = new ArrayList<>();
inventories.add(playerInventory.getHotbar());
inventories.add(playerInventory.getMain());
// Loop through replacing empty space with the requested items
for (Inventory inventory : inventories) {
List<ItemStackSnapshot> newBuffer = new ArrayList<>();
for (ItemStackSnapshot snapshot : itemBuffer) {
ItemStack stack = snapshot.createStack();
InventoryTransactionResult result = inventory.offer(stack);
newBuffer.addAll(result.getRejectedItems());
transactions.add(new Clause<>(stack, stack.getQuantity()));
}
itemBuffer = newBuffer;
}
// Drop remaining items
new ItemDropper(player.getLocation()).dropStackSnapshots(itemBuffer, SpawnTypes.PLUGIN);
return new Clause<>(true, transactions);
}
use of org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult in project LanternServer by LanternPowered.
the class AbstractEquipable method equip.
@Override
default boolean equip(EquipmentType type, @Nullable ItemStack equipment) {
checkNotNull(type, "type");
final Inventory inventory = getInventory().query(Holder.EQUIPMENT_INVENTORY_OPERATION);
if (inventory instanceof EmptyInventory) {
return false;
}
final AbstractSlot slot = (AbstractSlot) inventory.<IEquipmentInventory>first().getSlot(type).orElse(null);
if (slot == null) {
return false;
}
final InventoryTransactionResult result = slot.set(equipment);
return result.getType().equals(InventoryTransactionResult.Type.SUCCESS);
}
use of org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult in project Nucleus by NucleusPowered.
the class SkullCommand method executeCommand.
@Override
public CommandResult executeCommand(Player pl, CommandContext args) throws Exception {
User user = this.getUserFromArgs(User.class, pl, player, args);
int amount = args.<Integer>getOne(amountKey).orElse(1);
if (this.isUseMinecraftCommand) {
CommandResult result = Sponge.getCommandManager().process(Sponge.getServer().getConsole(), String.format("minecraft:give %s skull %d 3 {SkullOwner:%s}", pl.getName(), amount, user.getName()));
if (result.getSuccessCount().orElse(0) > 0) {
pl.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.skull.success.plural", String.valueOf(amount), user.getName()));
return result;
}
throw new ReturnMessageException(plugin.getMessageProvider().getTextMessageWithFormat("command.skull.error", user.getName()));
}
int fullStacks = amount / 64;
int partialStack = amount % 64;
// Create the Skull
ItemStack skullStack = ItemStack.builder().itemType(ItemTypes.SKULL).quantity(64).build();
// Set it to subject skull type and set the owner to the specified subject
if (skullStack.offer(Keys.SKULL_TYPE, SkullTypes.PLAYER).isSuccessful() && skullStack.offer(Keys.REPRESENTED_PLAYER, user.getProfile()).isSuccessful()) {
skullStack.toContainer().set(DataQuery.of("SkullOwner"), user.getName());
List<ItemStack> itemStackList = Lists.newArrayList();
// If there were stacks, create as many as needed.
if (fullStacks > 0) {
itemStackList.add(skullStack);
for (int i = 2; i <= fullStacks; i++) {
itemStackList.add(skullStack.copy());
}
}
// Same with the partial stacks.
if (partialStack > 0) {
ItemStack is = skullStack.copy();
is.setQuantity(partialStack);
itemStackList.add(is);
}
int accepted = 0;
int failed = 0;
Inventory inventoryToOfferTo = pl.getInventory().query(Hotbar.class, GridInventory.class);
for (ItemStack itemStack : itemStackList) {
int stackSize = itemStack.getQuantity();
InventoryTransactionResult itr = inventoryToOfferTo.offer(itemStack);
int currentFail = itr.getRejectedItems().stream().mapToInt(ItemStackSnapshot::getQuantity).sum();
failed += currentFail;
accepted += stackSize - currentFail;
}
// What was accepted?
if (accepted > 0) {
if (failed > 0) {
pl.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.skull.semifull", String.valueOf(failed)));
}
if (accepted == 1) {
pl.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.skull.success.single", user.getName()));
} else {
pl.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.skull.success.plural", String.valueOf(accepted), user.getName()));
}
return CommandResult.success();
}
pl.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.skull.full", user.getName()));
return CommandResult.empty();
} else {
pl.sendMessage(plugin.getMessageProvider().getTextMessageWithFormat("command.skull.error", user.getName()));
return CommandResult.empty();
}
}
use of org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult in project Nucleus by NucleusPowered.
the class KitHandler method addToStandardInventory.
/**
* Adds items to a {@link Player}s {@link Inventory}
* @param player The {@link Player}
* @param itemStacks The {@link ItemStackSnapshot}s to add.
* @param replaceTokensInLore If true, the display name
* @return {@link Tristate#TRUE} if everything is successful, {@link Tristate#FALSE} if nothing was added, {@link Tristate#UNDEFINED}
* if some stacks were added.
*/
private InventoryTransactionResult addToStandardInventory(Player player, Collection<ItemStackSnapshot> itemStacks, final boolean replaceTokensInLore) {
Inventory target = Util.getStandardInventory(player);
InventoryTransactionResult.Builder resultBuilder = InventoryTransactionResult.builder();
Collection<ItemStack> toOffer = itemStacks.stream().filter(x -> x.getType() != ItemTypes.NONE).map(ItemStackSnapshot::createStack).collect(Collectors.toList());
if (replaceTokensInLore) {
processTokensInItemStacks(player, toOffer);
}
boolean success = false;
for (ItemStack stack : toOffer) {
InventoryTransactionResult itr = target.offer(stack);
success = success || itr.getType() == InventoryTransactionResult.Type.SUCCESS;
for (ItemStackSnapshot iss : itr.getRejectedItems()) {
resultBuilder.reject(iss.createStack());
}
}
return resultBuilder.type(success ? InventoryTransactionResult.Type.SUCCESS : InventoryTransactionResult.Type.FAILURE).build();
}
use of org.spongepowered.api.item.inventory.transaction.InventoryTransactionResult in project Nucleus by NucleusPowered.
the class KitHandler method redeemKit.
public RedeemResult redeemKit(Kit kit, Player player, boolean performChecks, boolean isMustGetAll, boolean isFirstJoin) throws KitRedeemException {
KitUserDataModule user = Nucleus.getNucleus().getUserDataManager().get(player.getUniqueId()).get().get(KitUserDataModule.class);
Optional<Instant> oi = Util.getValueIgnoreCase(user.getKitLastUsedTime(), kit.getName());
Instant now = Instant.now();
if (performChecks) {
// If the kit was used before...
if (oi.isPresent()) {
// if it's one time only and the user does not have an exemption...
if (kit.isOneTime() && !player.hasPermission(cph.getPermissionWithSuffix("exempt.onetime"))) {
throw new KitRedeemException("Already redeemed", KitRedeemException.Reason.ALREADY_REDEEMED);
}
// bypass it...
if (!cph.testCooldownExempt(player) && kit.getCooldown().map(Duration::getSeconds).orElse(0L) > 0) {
// ...and we haven't reached the cooldown point yet...
Instant timeForNextUse = oi.get().plus(kit.getCooldown().get());
if (timeForNextUse.isAfter(now)) {
throw new KitRedeemException.Cooldown("Cooldown not expired", Duration.between(now, timeForNextUse));
}
}
}
}
// Kit pre redeem
Cause cause = CauseStackHelper.createCause(player);
NucleusKitEvent.Redeem.Pre preEvent = new KitEvent.PreRedeem(cause, oi.orElse(null), kit, player);
if (Sponge.getEventManager().post(preEvent)) {
throw new KitRedeemException.PreCancelled(preEvent.getCancelMessage().orElse(null));
}
List<Optional<ItemStackSnapshot>> slotList = Lists.newArrayList();
Util.getStandardInventory(player).slots().forEach(x -> slotList.add(x.peek().map(ItemStack::createSnapshot)));
InventoryTransactionResult inventoryTransactionResult = EMPTY_ITR;
if (!kit.getStacks().isEmpty()) {
inventoryTransactionResult = addToStandardInventory(player, kit.getStacks(), isProcessTokens);
if (!isFirstJoin && !inventoryTransactionResult.getRejectedItems().isEmpty() && isMustGetAll) {
Inventory inventory = Util.getStandardInventory(player);
// Slots
Iterator<Inventory> slot = inventory.slots().iterator();
// Slots to restore
slotList.forEach(x -> {
Inventory i = slot.next();
i.clear();
x.ifPresent(y -> i.offer(y.createStack()));
});
// My friend was playing No Man's Sky, I almost wrote "No free slots in suit inventory".
throw new KitRedeemException("No free slots in player inventory", KitRedeemException.Reason.NO_SPACE);
}
}
// If something was consumed, consider a success.
if (inventoryTransactionResult.getType() == InventoryTransactionResult.Type.SUCCESS) {
kit.redeemKitCommands(player);
// permissions or cooldowns change later
if (performChecks) {
user.addKitLastUsedTime(kit.getName(), now);
}
Sponge.getEventManager().post(new KitEvent.PostRedeem(cause, oi.orElse(null), kit, player));
return new KitRedeemResult(inventoryTransactionResult.getRejectedItems(), slotList.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()));
} else {
// Failed.
Sponge.getEventManager().post(new KitEvent.FailedRedeem(cause, oi.orElse(null), kit, player));
throw new KitRedeemException("No items were redeemed", KitRedeemException.Reason.UNKNOWN);
}
}
Aggregations