use of org.spongepowered.api.util.weighted.WeightedTable in project modules-extra by CubeEngine.
the class Spawner method onInteract.
@Listener(order = POST)
public void onInteract(InteractBlockEvent.Secondary event, @First Player player) {
if (!event.getTargetBlock().getLocation().isPresent()) {
return;
}
Location<World> block = event.getTargetBlock().getLocation().get();
if (block.getBlockType().equals(MOB_SPAWNER) && player.getItemInHand(MAIN_HAND).map(i -> i.getType().equals(ItemTypes.SPAWN_EGG)).orElse(false)) {
event.setCancelled(true);
if (block.get(SPAWNER_ENTITIES).map(RandomObjectTable::isEmpty).orElse(false)) {
ItemStack itemInHand = player.getItemInHand(MAIN_HAND).get();
EntityType type = itemInHand.get(Keys.SPAWNABLE_ENTITY_TYPE).get();
Permission perm = this.perms.get(type);
if (perm == null) {
this.initPerm(type);
perm = this.perms.get(type);
}
if (perm == null && !player.hasPermission(eggPerms.getId())) {
i18n.send(ACTION_BAR, player, NEGATIVE, "Invalid SpawnEgg!");
return;
}
if (perm != null && !player.hasPermission(perm.getId())) {
i18n.send(ACTION_BAR, player, NEGATIVE, "You are not allowed to change Monster Spawner to this EntityType!");
return;
}
WeightedTable<EntityArchetype> spawns = new WeightedTable<>();
EntityArchetype nextSpawn = EntityArchetype.builder().type(type).build();
spawns.add(nextSpawn, 1);
block.offer(SPAWNER_ENTITIES, spawns);
block.offer(SPAWNER_NEXT_ENTITY_TO_SPAWN, new WeightedSerializableObject<>(nextSpawn, 1));
if (!player.gameMode().get().equals(CREATIVE)) {
itemInHand.setQuantity(itemInHand.getQuantity() - 1);
player.setItemInHand(MAIN_HAND, itemInHand);
}
i18n.send(ACTION_BAR, player, POSITIVE, "Monster Spawner activated!");
return;
}
i18n.send(ACTION_BAR, player, NEGATIVE, "You can only change inactive Monster Spawner!");
}
}
use of org.spongepowered.api.util.weighted.WeightedTable in project SpongeAPI by SpongePowered.
the class ItemStackBuilderPopulators method values.
/**
* Creates a new {@link BiConsumer} that applies a random selection of the
* provided {@link BaseValue}s.
*
* <p>Note that custom data is not supported through this method, use
* {@link #data(Collection)} or any variant thereof for applying custom data.</p>
*
* @param values The iterable collection of values to choose from
* @param <E> The type of element
* @param <V> The type of value
* @return The new biconsumer to apply to an itemstack builder
*/
public static <E, V extends BaseValue<E>> BiConsumer<ItemStack.Builder, Random> values(Iterable<V> values) {
WeightedTable<V> tableEntries = new WeightedTable<>(1);
for (V value : values) {
tableEntries.add(checkNotNull(value, "Value cannot be null!"), 1);
}
return ((builder, random) -> {
final V value = tableEntries.get(random).get(0);
final ItemStack itemStack = builder.build();
final DataTransactionResult result = itemStack.offer(value);
if (result.isSuccessful()) {
builder.from(itemStack);
}
});
}
use of org.spongepowered.api.util.weighted.WeightedTable in project SpongeCommon by SpongePowered.
the class ItemStackData method register.
// @formatter:off
public static void register(final DataProviderRegistrator registrator) {
registrator.asMutable(ItemStack.class).create(Keys.APPLICABLE_POTION_EFFECTS).get(h -> {
if (h.isEdible()) {
final List<Pair<MobEffectInstance, Float>> itemEffects = h.getItem().getFoodProperties().getEffects();
final WeightedTable<PotionEffect> effects = new WeightedTable<>();
final ChanceTable<PotionEffect> chance = new ChanceTable<>();
for (final Pair<MobEffectInstance, Float> effect : itemEffects) {
chance.add((PotionEffect) effect.getFirst(), effect.getSecond());
}
effects.add(new NestedTableEntry<>(1, chance));
return effects;
}
return null;
}).create(Keys.BURN_TIME).get(h -> {
final Integer burnTime = AbstractFurnaceBlockEntity.getFuel().get(h.getItem());
if (burnTime != null && burnTime > 0) {
return burnTime;
}
return null;
}).create(Keys.CAN_HARVEST).get(h -> {
final Item item = h.getItem();
if (item instanceof DiggerItemAccessor && !(item instanceof PickaxeItem)) {
final Set<Block> blocks = ((DiggerItemAccessor) item).accessor$blocks();
return ImmutableSet.copyOf((Set<BlockType>) (Object) blocks);
}
final Set<BlockType> blockTypes = Registry.BLOCK.stream().filter(b -> item.isCorrectToolForDrops(b.defaultBlockState())).map(BlockType.class::cast).collect(ImmutableSet.toImmutableSet());
return blockTypes.isEmpty() ? null : blockTypes;
}).create(Keys.CONTAINER_ITEM).get(h -> (ItemType) h.getItem().getCraftingRemainingItem()).create(Keys.DISPLAY_NAME).get(h -> SpongeAdventure.asAdventure(h.getDisplayName())).create(Keys.CUSTOM_MODEL_DATA).get(h -> {
final CompoundTag tag = h.getTag();
if (tag == null || !tag.contains(Constants.Item.CUSTOM_MODEL_DATA, Constants.NBT.TAG_INT)) {
return null;
}
return tag.getInt(Constants.Item.CUSTOM_MODEL_DATA);
}).set((h, v) -> {
final CompoundTag tag = h.getOrCreateTag();
tag.putInt(Constants.Item.CUSTOM_MODEL_DATA, v);
}).delete(h -> {
final CompoundTag tag = h.getTag();
if (tag != null) {
tag.remove(Constants.Item.CUSTOM_MODEL_DATA);
}
}).create(Keys.CUSTOM_NAME).get(h -> {
if (h.hasCustomHoverName()) {
return SpongeAdventure.asAdventure(h.getHoverName());
}
if (h.getItem() == Items.WRITTEN_BOOK) {
// When no custom name is set on a written book fallback to its title
// The custom name has a higher priority than the title so no setter is needed.
final CompoundTag tag = h.getTag();
if (tag != null) {
final String title = tag.getString(Constants.Item.Book.ITEM_BOOK_TITLE);
return LegacyComponentSerializer.legacySection().deserialize(title);
}
}
return null;
}).set((h, v) -> h.setHoverName(SpongeAdventure.asVanilla(v))).delete(ItemStack::resetHoverName).create(Keys.IS_UNBREAKABLE).get(h -> {
final CompoundTag tag = h.getTag();
if (tag == null || !tag.contains(Constants.Item.ITEM_UNBREAKABLE, Constants.NBT.TAG_BYTE)) {
return false;
}
return tag.getBoolean(Constants.Item.ITEM_UNBREAKABLE);
}).set(ItemStackData::setIsUnbrekable).delete(h -> ItemStackData.setIsUnbrekable(h, false)).create(Keys.LORE).get(h -> {
final CompoundTag tag = h.getTag();
if (tag == null || !tag.contains(Constants.Item.ITEM_DISPLAY)) {
return null;
}
final CompoundTag displayCompound = tag.getCompound(Constants.Item.ITEM_DISPLAY);
final ListTag list = displayCompound.getList(Constants.Item.ITEM_LORE, Constants.NBT.TAG_STRING);
return list.isEmpty() ? null : SpongeAdventure.json(list.stream().collect(NBTCollectors.toStringList()));
}).set((h, v) -> {
if (v.isEmpty()) {
ItemStackData.deleteLore(h);
return;
}
final ListTag list = SpongeAdventure.listTagJson(v);
h.getOrCreateTagElement(Constants.Item.ITEM_DISPLAY).put(Constants.Item.ITEM_LORE, list);
}).delete(ItemStackData::deleteLore).create(Keys.MAX_DURABILITY).get(h -> h.getItem().canBeDepleted() ? h.getItem().getMaxDamage() : null).supports(h -> h.getItem().canBeDepleted()).create(Keys.ITEM_DURABILITY).get(stack -> stack.getMaxDamage() - stack.getDamageValue()).set((stack, durability) -> stack.setDamageValue(stack.getMaxDamage() - durability)).supports(h -> h.getItem().canBeDepleted()).create(Keys.ITEM_RARITY).get(stack -> (ItemRarity) (Object) stack.getRarity()).create(Keys.REPLENISHED_FOOD).get(h -> {
if (h.getItem().isEdible()) {
final FoodProperties food = h.getItem().getFoodProperties();
return food == null ? null : food.getNutrition();
}
return null;
}).supports(h -> h.getItem().isEdible()).create(Keys.REPLENISHED_SATURATION).get(h -> {
if (h.getItem().isEdible()) {
final FoodProperties food = h.getItem().getFoodProperties();
if (food != null) {
// Translate's Minecraft's weird internal value to the actual saturation value
return food.getSaturationModifier() * food.getNutrition() * 2.0;
}
}
return null;
}).supports(h -> h.getItem().isEdible());
}
use of org.spongepowered.api.util.weighted.WeightedTable in project SpongeCommon by SpongePowered.
the class SpawnerUtils method getEntities.
public static WeightedTable<EntityArchetype> getEntities(MobSpawnerBaseLogic logic) {
WeightedTable<EntityArchetype> possibleEntities = new WeightedTable<>();
for (WeightedSpawnerEntity weightedEntity : logic.potentialSpawns) {
NBTTagCompound nbt = weightedEntity.getNbt();
EntityType type = EntityUtil.fromNameToType(nbt.getString(NbtDataUtil.ENTITY_TYPE_ID)).orElse(EntityTypes.PIG);
EntityArchetype archetype = EntityArchetype.builder().type(type).entityData(NbtTranslator.getInstance().translateFrom(nbt)).build();
possibleEntities.add(new WeightedSerializableObject<>(archetype, weightedEntity.itemWeight));
}
return possibleEntities;
}
use of org.spongepowered.api.util.weighted.WeightedTable in project LanternServer by LanternPowered.
the class LanternWeatherUniverse method nextWeather.
/**
* Gets the next possible {@link LanternWeather}, ignoring
* the last weather type.
*
* @return The next weather type
*/
@SuppressWarnings("unchecked")
private LanternWeather nextWeather() {
final List<LanternWeather> weathers = new ArrayList(this.world.game.getRegistry().getAllOf(Weather.class));
final LanternWeather current = this.weatherData.getWeather();
weathers.remove(current);
if (weathers.isEmpty()) {
return current;
}
final WeightedTable<LanternWeather> table = new WeightedTable<>();
weathers.forEach(weather -> table.add(weather, weather.getWeight()));
return table.get(this.random).get(0);
}
Aggregations