Java Code Examples for net.minecraft.entity.player.InventoryPlayer#getStackInSlot()

The following examples show how to use net.minecraft.entity.player.InventoryPlayer#getStackInSlot() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ElectricStats.java    From GregTech with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void onUpdate(ItemStack itemStack, Entity entity) {
    IElectricItem electricItem = itemStack.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
    if(!entity.world.isRemote && entity instanceof EntityPlayer && electricItem != null &&
        electricItem.canProvideChargeExternally() &&
        isInDishargeMode(itemStack) && electricItem.getCharge() > 0L) {

        EntityPlayer entityPlayer = (EntityPlayer) entity;
        InventoryPlayer inventoryPlayer = entityPlayer.inventory;
        long transferLimit = electricItem.getTransferLimit();

        for(int i = 0; i < inventoryPlayer.getSizeInventory(); i++) {
            ItemStack itemInSlot = inventoryPlayer.getStackInSlot(i);
            IElectricItem slotElectricItem = itemInSlot.getCapability(GregtechCapabilities.CAPABILITY_ELECTRIC_ITEM, null);
            if(slotElectricItem != null && !slotElectricItem.canProvideChargeExternally()) {

                long chargedAmount = chargeElectricItem(transferLimit, electricItem, slotElectricItem);
                if(chargedAmount > 0L) {
                    transferLimit -= chargedAmount;
                    if(transferLimit == 0L) break;
                }
            }
        }
    }
}
 
Example 2
Source File: UpgradeResupply.java    From BetterChests with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void update(IUpgradableBlock chest, ItemStack stack) {
	IBetterChest inv = (IBetterChest)chest;
	IMobileUpgradableBlock bag = (IMobileUpgradableBlock) inv;
	Entity entity = bag.getEntity();
	if (entity instanceof EntityPlayer) {
		InventoryPlayer playerInv = ((EntityPlayer)entity).inventory;
		int currentSlot = UpgradeHelper.INSTANCE.getFrequencyTick(chest, stack, playerInv.getSizeInventory());
		IFilter filter = inv.getFilterFor(stack);
		ItemStack currentStack = playerInv.getStackInSlot(currentSlot);
		if (!currentStack.isEmpty() && filter.matchesStack(currentStack)) {
			int needed = (int) (currentStack.getMaxStackSize() / 2F + .5F) - currentStack.getCount();
			if (needed > 0) {
				int match = InvUtil.findInInvInternal(inv, null, test -> ItemUtil.areItemsSameMatchingIdDamageNbt(test, currentStack));
				if (match != -1) {
					ItemStack fromStack = inv.getStackInSlot(match);
					int toAdd = Math.min(needed, fromStack.getCount());
					currentStack.setCount(currentStack.getCount() + toAdd);
					fromStack.setCount(fromStack.getCount() - toAdd);
					inv.markDirty();
				}
			}
		}
	}
}
 
Example 3
Source File: TileEntityAerialInterface.java    From PneumaticCraft with GNU General Public License v3.0 6 votes vote down vote up
private void tickRF(){

        if(getEnergyStored(null) > 0) {
            InventoryPlayer inv = getPlayerInventory();
            if(inv != null) {
                for(int i = 0; i < inv.getSizeInventory(); i++) {
                    ItemStack stack = inv.getStackInSlot(i);
                    if(stack != null && stack.getItem() instanceof IEnergyContainerItem) {
                        IEnergyContainerItem chargingItem = (IEnergyContainerItem)stack.getItem();
                        int energyLeft = getEnergyStored(null);
                        if(energyLeft > 0) {
                            getEnergy().extractEnergy(chargingItem.receiveEnergy(stack, energyLeft, false), false);
                        } else {
                            break;
                        }
                    }
                }
            }
        }
    }
 
Example 4
Source File: ToroQuestCommand.java    From ToroQuest with GNU General Public License v3.0 5 votes vote down vote up
private List<ItemStack> pullHotbarItems(EntityPlayer player) {
	List<ItemStack> items = new ArrayList<ItemStack>();
	InventoryPlayer inv = player.inventory;

	for (int i = 0; i < inv.getSizeInventory(); i++) {
		if (inv.getStackInSlot(i) != null && InventoryPlayer.isHotbar(i)) {
			ItemStack stack = inv.getStackInSlot(i);
			inv.setInventorySlotContents(i, ItemStack.EMPTY);
			items.add(stack);
		}
	}

	return items;
}
 
Example 5
Source File: InfiniteStackSizeHandler.java    From NotEnoughItems with MIT License 5 votes vote down vote up
@Override
public void replenishInfiniteStack(InventoryPlayer inv, int slotNo) {
    ItemStack stack = inv.getStackInSlot(slotNo);
    stack.setCount(111);

    for (int i = 0; i < inv.getSizeInventory(); i++) {
        if (i == slotNo) {
            continue;
        }

        if (NEIServerUtils.areStacksSameType(stack, inv.getStackInSlot(i))) {
            inv.setInventorySlotContents(i, null);
        }
    }
}
 
Example 6
Source File: NEIController.java    From NotEnoughItems with MIT License 5 votes vote down vote up
public static void updateUnlimitedItems(InventoryPlayer inventory) {
    if (!NEIClientConfig.canPerformAction("item") || !NEIClientConfig.hasSMPCounterPart())
        return;

    LinkedList<ItemStack> beforeStacks = new LinkedList<ItemStack>();
    for (int i = 0; i < inventory.getSizeInventory(); i++)
        beforeStacks.add(NEIServerUtils.copyStack(inventory.getStackInSlot(i)));

    for (int i = 0; i < inventory.getSizeInventory(); i++) {
        ItemStack stack = inventory.getStackInSlot(i);
        if (stack == null)
            continue;

        for (IInfiniteItemHandler handler : ItemInfo.infiniteHandlers)
            if (handler.canHandleItem(stack) && handler.isItemInfinite(stack))
                handler.replenishInfiniteStack(inventory, i);
    }

    for (int i = 0; i < inventory.getSizeInventory(); i++) {
        ItemStack newstack = inventory.getStackInSlot(i);

        if (!NEIServerUtils.areStacksIdentical(beforeStacks.get(i), newstack)) {
            inventory.setInventorySlotContents(i, beforeStacks.get(i));//restore in case of SMP fail
            NEIClientUtils.setSlotContents(i, newstack, false);//sends via SMP handler ;)
        }
    }
}
 
Example 7
Source File: InfiniteStackSizeHandler.java    From NotEnoughItems with MIT License 5 votes vote down vote up
@Override
public void replenishInfiniteStack(InventoryPlayer inv, int slotNo)
{
    ItemStack stack = inv.getStackInSlot(slotNo);
    stack.stackSize = 111;
    
    for(int i = 0; i < inv.getSizeInventory(); i++)
    {
        if(i == slotNo)
            continue;
        
        if(NEIServerUtils.areStacksSameType(stack, inv.getStackInSlot(i)))
            inv.setInventorySlotContents(i, null);
    }
}
 
Example 8
Source File: TileEntityAerialInterface.java    From PneumaticCraft with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns the stack in slot i
 */
@Override
public ItemStack getStackInSlot(int slot){
    if(slot < 4) {
        return inventory[slot];
    } else {
        InventoryPlayer inventoryPlayer = getPlayerInventory();
        return inventoryPlayer != null ? slot == inventory.length + inventoryPlayer.getSizeInventory() ? null : inventoryPlayer.getStackInSlot(slot - 4) : null;
    }
}
 
Example 9
Source File: AutoToolHack.java    From ForgeWurst with GNU General Public License v3.0 4 votes vote down vote up
public void equipBestTool(BlockPos pos, boolean useSwords, boolean useHands,
	boolean repairMode)
{
	EntityPlayer player = WMinecraft.getPlayer();
	if(player.capabilities.isCreativeMode)
		return;
	
	IBlockState state = BlockUtils.getState(pos);
	
	ItemStack heldItem = player.getHeldItemMainhand();
	float bestSpeed = getDestroySpeed(heldItem, state);
	int bestSlot = -1;
	
	int fallbackSlot = -1;
	InventoryPlayer inventory = player.inventory;
	
	for(int slot = 0; slot < 9; slot++)
	{
		if(slot == inventory.currentItem)
			continue;
		
		ItemStack stack = inventory.getStackInSlot(slot);
		
		if(fallbackSlot == -1 && !isDamageable(stack))
			fallbackSlot = slot;
		
		float speed = getDestroySpeed(stack, state);
		if(speed <= bestSpeed)
			continue;
		
		if(!useSwords && stack.getItem() instanceof ItemSword)
			continue;
		
		if(isTooDamaged(stack, repairMode))
			continue;
		
		bestSpeed = speed;
		bestSlot = slot;
	}
	
	boolean useFallback =
		isDamageable(heldItem) && (isTooDamaged(heldItem, repairMode)
			|| useHands && getDestroySpeed(heldItem, state) <= 1);
	
	if(bestSlot != -1)
	{
		inventory.currentItem = bestSlot;
		return;
	}
	
	if(!useFallback)
		return;
	
	if(fallbackSlot != -1)
	{
		inventory.currentItem = fallbackSlot;
		return;
	}
	
	if(isTooDamaged(heldItem, repairMode))
		if(inventory.currentItem == 8)
			inventory.currentItem = 0;
		else
			inventory.currentItem++;
}
 
Example 10
Source File: PlaceCommandsImplementation.java    From malmo with MIT License 4 votes vote down vote up
@Override
protected boolean onExecute(String verb, String parameter, MissionInit missionInit) {
    EntityPlayerSP player = Minecraft.getMinecraft().player;
    if (player == null)
        return false;

    if (!verb.equalsIgnoreCase("place"))
        return false;

    Item item = Item.getByNameOrId(parameter);
    Block block = Block.getBlockFromItem(item);
    if (item == null || item.getRegistryName() == null || block.getRegistryName() == null)
        return false;

    InventoryPlayer inv = player.inventory;
    boolean blockInInventory = false;
    ItemStack stackInInventory = null;
    int stackIndex = -1;
    for (int i = 0; !blockInInventory && i < inv.getSizeInventory(); i++) {
        Item stack = inv.getStackInSlot(i).getItem();
        if (stack.getRegistryName() != null && stack.getRegistryName().equals(item.getRegistryName())) {
            stackInInventory = inv.getStackInSlot(i);
            stackIndex = i;
            blockInInventory = true;
        }
    }

    // We don't have that item in our inventories
    if (!blockInInventory)
        return false;

    RayTraceResult mop = Minecraft.getMinecraft().objectMouseOver;
    if (mop.typeOfHit == RayTraceResult.Type.BLOCK) {
        BlockPos pos = mop.getBlockPos().add(mop.sideHit.getDirectionVec());
        // Can we place this block here?
        AxisAlignedBB axisalignedbb = block.getDefaultState().getCollisionBoundingBox(player.world, pos);
        if (axisalignedbb == null || player.world.checkNoEntityCollision(axisalignedbb.offset(pos), null)) {
            MalmoMod.network.sendToServer(new DiscreteMovementCommandsImplementation.UseActionMessage(mop.getBlockPos(), new ItemStack(block), mop.sideHit, false, mop.hitVec));
            if (stackInInventory.getCount() == 1)
                inv.setInventorySlotContents(stackIndex, new ItemStack(Block.getBlockById(0)));
            else
                stackInInventory.setCount(stackInInventory.getCount() - 1);
        }
    }

    return true;
}
 
Example 11
Source File: TileEntityQuantumComputer.java    From qcraft-mod with Apache License 2.0 4 votes vote down vote up
public static void teleportPlayerRemote( EntityPlayer player, String remoteServerAddress, String remotePortalID, boolean takeItems )
{
    // Log the trip
    QCraft.log( "Sending player " + player.getDisplayName() + " to server \"" + remoteServerAddress + "\"" );

    NBTTagCompound luggage = new NBTTagCompound();
    if( takeItems )
    {
        // Remove and encode the items from the players inventory we want them to take with them
        NBTTagList items = new NBTTagList();
        InventoryPlayer playerInventory = player.inventory;
        for( int i = 0; i < playerInventory.getSizeInventory(); ++i )
        {
            ItemStack stack = playerInventory.getStackInSlot( i );
            if( stack != null && stack.stackSize > 0 )
            {
                // Ignore entangled items
                if( stack.getItem() == Item.getItemFromBlock( QCraft.Blocks.quantumComputer ) && ItemQuantumComputer.getEntanglementFrequency( stack ) >= 0 )
                {
                    continue;
                }
                if( stack.getItem() == Item.getItemFromBlock( QCraft.Blocks.qBlock ) && ItemQBlock.getEntanglementFrequency( stack ) >= 0 )
                {
                    continue;
                }

                // Store items
                NBTTagCompound itemTag = new NBTTagCompound();
                if (stack.getItem() == QCraft.Items.missingItem) {
                    itemTag = stack.stackTagCompound;
                } else {
                    GameRegistry.UniqueIdentifier uniqueId = GameRegistry.findUniqueIdentifierFor(stack.getItem());
                    String itemName = uniqueId.modId + ":" + uniqueId.name;
                    itemTag.setString("Name", itemName);
                    stack.writeToNBT( itemTag );
                }
                items.appendTag( itemTag );

                // Remove items
                playerInventory.setInventorySlotContents( i, null );
            }
        }

        if( items.tagCount() > 0 )
        {
            QCraft.log( "Removed " + items.tagCount() + " items from " + player.getDisplayName() + "'s inventory." );
            playerInventory.markDirty();
            luggage.setTag( "items", items );
        }
    }

    // Set the destination portal ID
    if( remotePortalID != null )
    {
        luggage.setString( "destinationPortal", remotePortalID );
    }

    try
    {
        // Cryptographically sign the luggage
        luggage.setString( "uuid", UUID.randomUUID().toString() );
        byte[] luggageData = CompressedStreamTools.compress( luggage );
        byte[] luggageSignature = EncryptionRegistry.Instance.signData( luggageData );
        NBTTagCompound signedLuggage = new NBTTagCompound();
        signedLuggage.setByteArray( "key", EncryptionRegistry.Instance.encodePublicKey( EncryptionRegistry.Instance.getLocalKeyPair().getPublic() ) );
        signedLuggage.setByteArray( "luggage", luggageData );
        signedLuggage.setByteArray( "signature", luggageSignature );

        // Send the player to the remote server with the luggage
        byte[] signedLuggageData = CompressedStreamTools.compress( signedLuggage );
        QCraft.requestGoToServer( player, remoteServerAddress, signedLuggageData );
    }
    catch( IOException e )
    {
        throw new RuntimeException( "Error encoding inventory" );
    }
    finally
    {
        // Prevent the player from being warped twice
        player.timeUntilPortal = 200;
    }
}
 
Example 12
Source File: TileEntityChargingStation.java    From PneumaticCraft with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void updateEntity(){
    disCharging = false;
    charging = false;
    List<IPressurizable> chargingItems = new ArrayList<IPressurizable>();
    List<ItemStack> chargedStacks = new ArrayList<ItemStack>();
    if(inventory[CHARGE_INVENTORY_INDEX] != null && inventory[CHARGE_INVENTORY_INDEX].getItem() instanceof IPressurizable) {
        chargingItems.add((IPressurizable)inventory[CHARGE_INVENTORY_INDEX].getItem());
        chargedStacks.add(inventory[CHARGE_INVENTORY_INDEX]);
    }
    if(this.getUpgrades(ItemMachineUpgrade.UPGRADE_DISPENSER_DAMAGE) > 0) {
        //creating a new word, 'entities padding'.
        List<Entity> entitiesPadding = worldObj.getEntitiesWithinAABB(Entity.class, AxisAlignedBB.getBoundingBox(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 2, zCoord + 1));
        for(Entity entity : entitiesPadding) {
            if(entity instanceof IPressurizable) {
                chargingItems.add((IPressurizable)entity);
                chargedStacks.add(null);
            } else if(entity instanceof EntityItem) {
                ItemStack entityStack = ((EntityItem)entity).getEntityItem();
                if(entityStack != null && entityStack.getItem() instanceof IPressurizable) {
                    chargingItems.add((IPressurizable)entityStack.getItem());
                    chargedStacks.add(entityStack);
                }
            } else if(entity instanceof EntityPlayer) {
                InventoryPlayer inv = ((EntityPlayer)entity).inventory;
                for(int i = 0; i < inv.getSizeInventory(); i++) {
                    ItemStack stack = inv.getStackInSlot(i);
                    if(stack != null && stack.getItem() instanceof IPressurizable) {
                        chargingItems.add((IPressurizable)stack.getItem());
                        chargedStacks.add(stack);
                    }
                }
            }
        }
    }
    int speedMultiplier = (int)getSpeedMultiplierFromUpgrades(getUpgradeSlots());
    for(int i = 0; i < PneumaticValues.CHARGING_STATION_CHARGE_RATE * speedMultiplier; i++) {
        boolean charged = false;
        for(int j = 0; j < chargingItems.size(); j++) {
            IPressurizable chargingItem = chargingItems.get(j);
            ItemStack chargedItem = chargedStacks.get(j);
            if(chargingItem.getPressure(chargedItem) > getPressure(ForgeDirection.UNKNOWN) + 0.01F && chargingItem.getPressure(chargedItem) > 0F) {
                if(!worldObj.isRemote) {
                    chargingItem.addAir(chargedItem, -1);
                    addAir(1, ForgeDirection.UNKNOWN);
                }
                disCharging = true;
                renderAirProgress -= ANIMATION_AIR_SPEED;
                if(renderAirProgress < 0.0F) {
                    renderAirProgress += 1F;
                }
                charged = true;
            } else if(chargingItem.getPressure(chargedItem) < getPressure(ForgeDirection.UNKNOWN) - 0.01F && chargingItem.getPressure(chargedItem) < chargingItem.maxPressure(chargedItem)) {// if there is pressure, and the item isn't fully charged yet..
                if(!worldObj.isRemote) {
                    chargingItem.addAir(chargedItem, 1);
                    addAir(-1, ForgeDirection.UNKNOWN);
                }
                charging = true;
                renderAirProgress += ANIMATION_AIR_SPEED;
                if(renderAirProgress > 1.0F) {
                    renderAirProgress -= 1F;
                }
                charged = true;
            }
        }
        if(!charged) break;
    }

    if(!worldObj.isRemote && oldRedstoneStatus != shouldEmitRedstone()) {
        oldRedstoneStatus = shouldEmitRedstone();
        updateNeighbours();
    }

    super.updateEntity();

}