下面列出了怎么用net.minecraft.util.NonNullList的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void getSubItems(@Nullable CreativeTabs tab, @Nonnull NonNullList<ItemStack> subItems) {
if (isInCreativeTab(tab)) {
subItems.add(new ItemStack(this));
for (int i = 1; i < 10; i++) {
ItemStack stack = new ItemStack(this, 1, 1);
ManaManager.forObject(stack)
.setMana(ManaManager.getMaxMana(stack) * i / 10.0)
.close();
subItems.add(stack);
}
subItems.add(new ItemStack(this, 1, 1));
}
}
@Test
public void test_createSubItems_differentTabs()
{
HashMap<Integer, String> map = Maps.newHashMap();
map.put(0, "tools");
map.put(1, "redstone");
Attribute<String> tabLabels = Attribute.map(map);
int[] subtypes = new int[] {0, 1};
Item item = new Item();
item.setHasSubtypes(true);
NonNullList<ItemStack> subItems = ItemHelper.createSubItems(item, CreativeTabs.TOOLS, tabLabels, subtypes);
assertSame(1, subItems.size());
assertSame(0, subItems.get(0).getItemDamage());
}
@Test
public void test_createSubItems_search_tab()
{
HashMap<Integer, String> map = Maps.newHashMap();
map.put(0, "tools");
map.put(1, "redstone");
Attribute<String> tabLabels = Attribute.map(map);
int[] subtypes = new int[] {0, 1};
Item item = new Item();
item.setHasSubtypes(true);
NonNullList<ItemStack> subItems = ItemHelper.createSubItems(item, CreativeTabs.SEARCH, tabLabels, subtypes);
assertEquals(2, subItems.size());
assertEquals(0, subItems.get(0).getItemDamage());
assertEquals(1, subItems.get(1).getItemDamage());
}
/**
* Inspect a player's inventory to see whether they have enough items to form the supplied list of ItemStacks.<br>
* The ingredients list MUST be amalgamated such that no two ItemStacks contain the same type of item.
*
* @param player
* @param ingredients an amalgamated list of ingredients
* @return true if the player's inventory contains sufficient quantities of all the required items.
*/
public static boolean playerHasIngredients(EntityPlayerMP player, List<ItemStack> ingredients) {
NonNullList<ItemStack> main = player.inventory.mainInventory;
NonNullList<ItemStack> arm = player.inventory.armorInventory;
for (ItemStack isIngredient : ingredients) {
int target = isIngredient.getCount();
for (int i = 0; i < main.size() + arm.size() && target > 0; i++) {
ItemStack isPlayer = (i >= main.size()) ? arm.get(i - main.size()) : main.get(i);
if (isPlayer != null && isIngredient != null && itemStackIngredientsMatch(isPlayer, isIngredient))
target -= isPlayer.getCount();
}
if (target > 0)
return false; // Don't have enough of this.
}
return true;
}
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {
Random rand = world instanceof World ? ((World) world).rand : RANDOM;
int age = getAge(state);
int count = quantityDropped(state, fortune, rand);
for (int i = 0; i < count; i++) {
Item item = this.getItemDropped(state, rand, fortune);
if (item != Items.AIR) {
drops.add(new ItemStack(item, 1, this.damageDropped(state)));
}
}
if (age >= getMaxAge()) {
int k = 3 + fortune;
for (int i = 0; i < k; ++i) {
if (rand.nextInt(2 * getMaxAge()) <= age) {
drops.add(new ItemStack(this.getSeed(), 1, this.damageDropped(state)));
}
}
}
}
private static void registerAllItemBlockModels(BlockEnderUtilities blockIn, String variantPre, String variantPost)
{
if (blockIn.isEnabled())
{
NonNullList<ItemStack> stacks = NonNullList.create();
blockIn.getSubBlocks(blockIn.getCreativeTab(), stacks);
String[] names = blockIn.getUnlocalizedNames();
for (ItemStack stack : stacks)
{
Item item = stack.getItem();
int meta = stack.getMetadata();
ModelResourceLocation mrl = new ModelResourceLocation(item.getRegistryName(), variantPre + names[meta] + variantPost);
ModelLoader.setCustomModelResourceLocation(item, meta, mrl);
}
}
}
@Test
public void test_useUpItem()
{
DamageableShapelessOreRecipe recipe = new DamageableShapelessOreRecipe(new ResourceLocation("group"),
new int[] {60}, new ItemStack(Blocks.DIRT), new ItemStack(Items.WOODEN_SWORD));
InventoryCrafting inv = new InventoryCrafting(new Container()
{
@Override
public boolean canInteractWith(EntityPlayer playerIn)
{
return false;
}
}, 3, 3);
inv.setInventorySlotContents(3, new ItemStack(Items.WOODEN_SWORD));
assertTrue(recipe.matches(inv, null));
NonNullList<ItemStack> remaining = recipe.getRemainingItems(inv);
assertTrue(remaining.get(3).isEmpty());
}
@Override
public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv) {
NonNullList<ItemStack> remains = ForgeHooks.defaultRecipeGetRemainingItems(inv);
for (int i = 0; i < height * width; i++) {
ItemStack stack = inv.getStackInSlot(i);
NonNullList<Ingredient> matchedIngredients = this.input;
if (matchedIngredients.get(i) instanceof IngredientFluidStack) {
if (!stack.isEmpty()) {
ItemStack copy = stack.copy();
copy.setCount(1);
remains.set(i, copy);
}
IFluidHandlerItem handler = FluidUtil.getFluidHandler(remains.get(i));
if (handler != null) {
FluidStack fluid = ((IngredientFluidStack) matchedIngredients.get(i)).getFluid();
handler.drain(fluid.amount, true);
remains.set(i, handler.getContainer());
}
}
}
return remains;
}
@Override
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune)
{
if (content.snowball != null)
{
ItemStack stack = content.snowball.getItemStack().copy();
stack.setCount((state.getValue(LAYERS) + 1) * stack.getCount());
drops.add(stack);
}
Optional<BlockDrop[]> blockDrops = getContent().drop.get(getSubtype(state));
if (blockDrops.isPresent())
{
drops.addAll(ItemHelper.getDroppedStacks(blockDrops.get(), fortune));
}
}
public static NonNullList<ItemStack> createSubItems(Item item, CreativeTabs creativeTab, Attribute<String> tabLabels, int[] subtypes)
{
NonNullList<ItemStack> list = NonNullList.create();
if (item.getHasSubtypes())
{
for (int meta : subtypes)
{
tabLabels.get(meta)
.ifPresent(tabLabel ->
{
if (creativeTab == null || creativeTab == CreativeTabs.SEARCH || Objects.equals(tabLabel, getTabLabel(creativeTab)))
{
list.add(new ItemStack(item, 1, meta));
}
});
}
} else
{
list.add(new ItemStack(item, 1, 0));
}
return list;
}
public Recipe(List<CountableIngredient> inputs, List<ItemStack> outputs, List<ChanceEntry> chancedOutputs,
List<FluidStack> fluidInputs, List<FluidStack> fluidOutputs,
Map<String, Object> recipeProperties, int duration, int EUt, boolean hidden) {
this.recipeProperties = ImmutableMap.copyOf(recipeProperties);
this.inputs = NonNullList.create();
this.inputs.addAll(inputs);
this.outputs = NonNullList.create();
this.outputs.addAll(outputs);
this.chancedOutputs = new ArrayList<>(chancedOutputs);
this.fluidInputs = ImmutableList.copyOf(fluidInputs);
this.fluidOutputs = ImmutableList.copyOf(fluidOutputs);
this.duration = duration;
this.EUt = EUt;
this.hidden = hidden;
//sort input elements in descending order (i.e not consumables inputs are last)
this.inputs.sort(Comparator.comparing(CountableIngredient::getCount).reversed());
}
@Test
public void test_deserializer()
{
MachineRecipeImpl recipe = gson.fromJson("{" +
"\"recipeList\": \"cs4examplemod:machine\"," +
"\"input\": [\"minecraft:apple\", \"minecraft:gold_ingot\"]," +
"\"output\": \"minecraft:golden_apple\"," +
"\"inputFluid\": [\"[email protected]\"]," +
"\"cookTime\": 400" + "}", MachineRecipeImpl.class);
recipe.init(InitPhase.PRE_INIT, null);
List<RecipeInput> inputItems = recipe.getRecipeInput();
List<FluidStack> inputFluids = recipe.getFluidRecipeInput();
NonNullList<MachineRecipeOutput> outputs = recipe.getOutputs();
MachineRecipeOutput output = outputs.get(0);
assertEquals(400, recipe.getCookTime());
assertEquals(2, inputItems.size());
assertEquals(1, inputFluids.size());
assertEquals(1, outputs.size());
assertEquals(1, output.getWeight());
assertEquals(1, output.getOutputItems().size());
assertEquals(0, output.getOutputFluids().size());
}
private boolean isSameInputs(NonNullList<Ingredient> targetInput)
{
Object[] sourceInput = getRecipeInput();
for (int i = 0; i < targetInput.size(); i++)
{
Ingredient target = targetInput.get(i);
Object source = sourceInput[i];
if (!ItemHelper.isSameRecipeInput(target, source))
return false;
}
return true;
}
public static List<NonNullList<ItemStack>> getOreIdStacksUn() {
try {
return (List<NonNullList<ItemStack>>) OREDICTIONARY_IDTOSTACKUN.get(null);
} catch (IllegalAccessException ex) {
Game.logger().error("ERROR - could not load ore dictionary stacks!");
return null;
}
}
@Override
public void readFromNBT(NBTTagCompound c) {
super.readFromNBT(c);
processor.readFromNBT(c.getCompoundTag(NBT_PROCESSOR));
codeItemStacks = NonNullList.<ItemStack>withSize(this.getSizeInventory(), ItemStack.EMPTY);
ItemStackHelper.loadAllItems(c, codeItemStacks);
loadTime = c.getShort(NBT_LOAD_TIME);
if (c.hasKey(NBT_CUSTOM_NAME, 8)) {
this.customName = c.getString(NBT_CUSTOM_NAME);
}
}
@Override
public void getSubItems(@Nullable CreativeTabs tab, @Nonnull NonNullList<ItemStack> subItems) {
if (isInCreativeTab(tab)) {
subItems.add(new ItemStack(this));
ItemStack stack = new ItemStack(this);
NBTHelper.setFloat(stack, NBTConstants.NBT.PURITY_OVERRIDE, 2f);
subItems.add(stack);
}
}
public static NonNullList<ItemStack> readStackArrayFromNBTList(NBTTagList list, int size)
{
NonNullList<ItemStack> out = NonNullList.<ItemStack>withSize(size, ItemStack.EMPTY);
for(int i = 0; i < list.tagCount(); i++)
{
NBTTagCompound tag = list.getCompoundTagAt(i);
byte byte0 = tag.getByte("Slot");
if(byte0 >= 0 && byte0 < size)
out.set(byte0, new ItemStack(tag));
}
return out;
}
@Override
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state,
int fortune) {
if(getFerm(state)!=8){
drops.clear();
drops.add(new ItemStack(state.getBlock()));
}else
super.getDrops(drops, world, pos, state, fortune);
}
@Override
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state,
int fortune) {
if (!canFerm(state)) {
drops.add(drop);
} else {
for (ItemStack stack : in) {
drops.add(stack);
}
}
super.getDrops(drops, world, pos, state, fortune);
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list)
{
for (int i = 0; i < BridgeType.values().length; i++)
{
list.add(new ItemStack(this, 1, BridgeType.values()[i].getMeta()));
}
}
public void readPacketNBT(NBTTagCompound cmp) {
this.inventory =
NonNullList.withSize(this.getSizeInventory(), ItemStack.EMPTY);
ItemStackHelper.loadAllItems(cmp, this.inventory);
this.workload = cmp.getInteger("workload");
this.current_workload = cmp.getInteger("current");
this.tank.readFromNBT(cmp.getCompoundTag("Tank"));
}
@Override
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) {
if (this.isInCreativeTab(tab)) {
ItemStack empty = new ItemStack(this, 1, 0);
ItemStack full = new ItemStack(this, 1, 0);
ElectricItem.manager.discharge(empty, 2.147483647E9D, Integer.MAX_VALUE, true, false, false);
ElectricItem.manager.charge(full, 2.147483647E9D, Integer.MAX_VALUE, true, false);
items.add(empty);
items.add(full);
}
}
@Override
public void getSubBlocks(CreativeTabs tab, NonNullList<ItemStack> list)
{
for (int i = 0; i < EnumStorageType.values().length; i++)
{
list.add(new ItemStack(this, 1, EnumStorageType.values()[i].getMeta()));
}
}
public TileEntityCreationStation()
{
super(ReferenceNames.NAME_TILE_ENTITY_CREATION_STATION);
this.itemHandlerBase = new ItemStackHandlerTileEntity(INV_ID_MODULES, 4, 1, false, "Items", this);
this.itemHandlerMemoryCards = new TileEntityHandyChest.ItemHandlerWrapperMemoryCards(this.getBaseItemHandler());
this.craftingInventories = new InventoryItemCallback[2];
this.craftingGridTemplates = new ArrayList<NonNullList<ItemStack>>();
this.craftingGridTemplates.add(null);
this.craftingGridTemplates.add(null);
this.recipeItems0 = NonNullList.withSize(10, ItemStack.EMPTY);
this.recipeItems1 = NonNullList.withSize(10, ItemStack.EMPTY);
this.craftResults = new ItemHandlerCraftResult[] { new ItemHandlerCraftResult(), new ItemHandlerCraftResult() };
this.furnaceInventory = new ItemStackHandlerTileEntity(INV_ID_FURNACE, 6, 1024, true, "FurnaceItems", this);
this.furnaceInventoryWrapper = new ItemHandlerWrapperFurnace(this.furnaceInventory);
this.clickTimes = new HashMap<UUID, Long>();
this.smeltingResultCache = new ItemStack[] { ItemStack.EMPTY, ItemStack.EMPTY };
this.burnTimeRemaining = new int[2];
this.burnTimeFresh = new int[2];
this.cookTime = new int[2];
this.inputDirty = new boolean[] { true, true };
this.modeMask = 0;
}
@Override
public ItemStack onTake(EntityPlayer thePlayer, ItemStack stack)
{
this.onCrafting(stack);
net.minecraftforge.common.ForgeHooks.setCraftingPlayer(thePlayer);
NonNullList<ItemStack> nonnulllist = CraftingManagerTFC.getInstance().getRemainingItems(this.craftMatrix, thePlayer.world);
net.minecraftforge.common.ForgeHooks.setCraftingPlayer(null);
for (int i = 0; i < nonnulllist.size(); ++i)
{
ItemStack itemstack = this.craftMatrix.getStackInSlot(i);
ItemStack itemstack1 = (ItemStack)nonnulllist.get(i);
if (!itemstack.isEmpty())
{
this.craftMatrix.decrStackSize(i, 1);
itemstack = this.craftMatrix.getStackInSlot(i);
}
if (!itemstack1.isEmpty())
{
if (itemstack.isEmpty())
{
this.craftMatrix.setInventorySlotContents(i, itemstack1);
}
else if (ItemStack.areItemsEqual(itemstack, itemstack1) && ItemStack.areItemStackTagsEqual(itemstack, itemstack1))
{
itemstack1.grow(itemstack.getCount());
this.craftMatrix.setInventorySlotContents(i, itemstack1);
}
else if (!this.player.inventory.addItemStackToInventory(itemstack1))
{
this.player.dropItem(itemstack1, false);
}
}
}
return stack;
}
@Override
public void getSubItemsCustom(CreativeTabs creativeTab, NonNullList<ItemStack> list)
{
for (int i = 0; i < 4; i++)
{
list.add(new ItemStack(this, 1, i));
}
}
public void restockCraftingGrid(IItemHandler invCrafting, int invId)
{
invId = MathHelper.clamp(invId, 0, 1);
NonNullList<ItemStack> template = this.craftingGridTemplates.get(invId);
if (invCrafting == null || template == null)
{
return;
}
this.recipeLoadClickCount = 0;
int maskAutoUse = invId == 1 ? MODE_BIT_RIGHT_CRAFTING_AUTOUSE : MODE_BIT_LEFT_CRAFTING_AUTOUSE;
// Auto-use feature not enabled
if ((this.modeMask & maskAutoUse) == 0)
{
return;
}
int maskOreDict = invId == 1 ? MODE_BIT_RIGHT_CRAFTING_OREDICT : MODE_BIT_LEFT_CRAFTING_OREDICT;
boolean useOreDict = (this.modeMask & maskOreDict) != 0;
InventoryUtils.clearInventoryToMatchTemplate(invCrafting, this.itemInventory, template);
InventoryUtils.restockInventoryBasedOnTemplate(invCrafting, this.itemInventory, template, 1, true, useOreDict);
this.craftingGridTemplates.set(invId, null);
}
private boolean tryPickNewRecipe() {
ItemStack inputStack = importItems.getStackInSlot(0);
ItemStack fuelStack = importItems.getStackInSlot(1);
if (inputStack.isEmpty() || (fuelStack.isEmpty() && fuelUnitsLeft == 0)) {
return false;
}
float fuelUnitsPerItem = getFuelUnits(fuelStack);
float totalFuelUnits = fuelUnitsLeft + fuelUnitsPerItem * fuelStack.getCount();
PrimitiveBlastFurnaceRecipe currentRecipe = getOrRefreshRecipe(inputStack);
if (currentRecipe != null && setupRecipe(inputStack, (int) totalFuelUnits, currentRecipe)) {
inputStack.shrink(currentRecipe.getInput().getCount());
float fuelUnitsToConsume = currentRecipe.getFuelAmount();
float remainderConsumed = Math.min(fuelUnitsToConsume, fuelUnitsLeft);
fuelUnitsToConsume -= remainderConsumed;
int fuelItemsToConsume = (int) Math.ceil(fuelUnitsToConsume / (fuelUnitsPerItem * 1.0));
float remainderAdded = fuelItemsToConsume * fuelUnitsPerItem - fuelUnitsToConsume;
this.fuelUnitsLeft += (remainderAdded - remainderConsumed);
fuelStack.shrink(fuelItemsToConsume);
this.maxProgressDuration = currentRecipe.getDuration();
this.currentProgress = 0;
NonNullList<ItemStack> outputs = NonNullList.create();
outputs.add(currentRecipe.getOutput().copy());
outputs.add(getAshForRecipeFuelConsumption(currentRecipe.getFuelAmount()));
this.outputsList = outputs;
markDirty();
return true;
}
return false;
}
@Override
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) {
if (!isInCreativeTab(tab)) {
return;
}
ItemStack empty = new ItemStack(this, 1, 0);
ItemStack full = new ItemStack(this, 1, 0);
ElectricItem.manager.discharge(empty, 2.147483647E9D, Integer.MAX_VALUE, true, false, false);
ElectricItem.manager.charge(full, 2.147483647E9D, Integer.MAX_VALUE, true, false);
items.add(empty);
items.add(full);
}
@Override
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) {
if (!isInCreativeTab(tab)) {
return;
}
ItemStack empty = new ItemStack(this, 1, 0);
ItemStack full = new ItemStack(this, 1, 0);
ElectricItem.manager.discharge(empty, 2.147483647E9D, Integer.MAX_VALUE, true, false, false);
ElectricItem.manager.charge(full, 2.147483647E9D, Integer.MAX_VALUE, true, false);
empty.addEnchantment(Enchantments.SILK_TOUCH, 1);
full.addEnchantment(Enchantments.SILK_TOUCH, 1);
items.add(empty);
items.add(full);
}