Jump to content

[1.10.2] Problems with container slots and shift click


Dustpuppy

Recommended Posts

Hi,

i have problems with an container. It works, if i don't use transferStackInSlot, but shift clicking will not work. It moves the items to wrong slots and sometime it double them or even don't show.

 

The container class

Spoiler

package helpinghands.People;

import helpinghands.People.Entities.EntityWorker;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;

public class ContainerWorker extends Container {

    private EntityWorker entity;
    private InventoryWorker entityInventory;

    public ContainerWorker(IInventory playerInv, EntityWorker entity) {
        	this.entity = entity;
        	this.entityInventory = entity.inventory;
        
        	int slot = 0;
        
        	// Entity, Slot 0-8
            for (int x = 0; x < 9; ++x) {
                this.addSlotToContainer(new Slot(entityInventory, slot++, 30 + x * 18, 60));
            }

            // Player Inventory, Slot 9-35
            for (int y = 0; y < 3; ++y) {
                for (int x = 0; x < 9; ++x) {
                    this.addSlotToContainer(new Slot(playerInv, slot++, 30 + x * 18, 91 + y * 18));
                }
            }
            
            // Player Inventory, Slot 36-44
            for (int x = 0; x < 9; ++x) {
                this.addSlotToContainer(new Slot(playerInv, slot++, 30 + x * 18, 149));
            }

    }

    @Override
    public boolean canInteractWith(EntityPlayer playerIn) {
        return true;
    }

    
    @Override
    public ItemStack transferStackInSlot(EntityPlayer playerIn, int fromSlot) {
    	System.out.println(fromSlot);
    	
        ItemStack previous = null;
        Slot slot = (Slot) this.inventorySlots.get(fromSlot);

        if (slot != null && slot.getHasStack()) {
            ItemStack current = slot.getStack();
            previous = current.copy();

            if (fromSlot < 9) {
                // From Entity Inventory to Player Inventory
                if (!this.mergeItemStack(current, 9, 45, true))
                    return null;
            } else {
                // From Player Inventory to Entity Inventory
                if (!this.mergeItemStack(current, 0, 9, false))
                    return null;
            }

            if (current.stackSize == 0)
                slot.putStack((ItemStack) null);
            else
                slot.onSlotChanged();

            slot.onPickupFromSlot(playerIn, current);
        }
        return previous;
    }
}

 

The entity

Spoiler


package helpinghands.People.Entities;

import helpinghands.HelpingHands;
import helpinghands.GuiHandler.GuiHandler;
import helpinghands.People.InventoryWorker;
import helpinghands.People.AI.EntityAIMoveTo;
import helpinghands.People.AI.EntityAIOpenGate;
import helpinghands.events.PacketHelpingHands;

import java.io.IOException;

import javax.annotation.Nullable;

import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIMoveIndoors;
import net.minecraft.entity.ai.EntityAIOpenDoor;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAITasks.EntityAITaskEntry;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.pathfinding.PathNavigateGround;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class EntityWorker extends EntityCreature{

	public EntityTyp profession;
	public boolean selected;
	public BlockPos destinationPos;

	public EntityAIBase aiMoveTo = null;
	
    public InventoryWorker inventory;

    public EntityWorker(World worldIn) {
        super(worldIn);
        this.profession = EntityTyp.DEFAULT;
    	this.setDropItemsWhenDead(false);
    	this.selected = false;
        ((PathNavigateGround)this.getNavigator()).setBreakDoors(true);
        ((PathNavigateGround)this.getNavigator()).setEnterDoors(true);
        ((PathNavigateGround)this.getNavigator()).setCanSwim(true);
        this.inventory = new InventoryWorker(this);
    }

    @Override
    protected void entityInit() {
        super.entityInit();
    }

    @Override
    protected void applyEntityAttributes() {
        super.applyEntityAttributes();
        // Here we set various attributes for our mob. Like maximum health, armor, speed, ...
        this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(15F);
        this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.3D);
        this.getEntityAttribute(SharedMonsterAttributes.FOLLOW_RANGE).setBaseValue(32.0D);
        this.getEntityAttribute(SharedMonsterAttributes.ARMOR).setBaseValue(2.0D);
        }


    @Override
    protected void initEntityAI() {
        this.tasks.addTask(0, new EntityAISwimming(this));
        this.tasks.addTask(10, new EntityAIMoveIndoors(this));
        this.tasks.addTask(11, new EntityAIOpenDoor(this, true));
        this.tasks.addTask(12, new EntityAIOpenGate(this, true));
        this.tasks.addTask(13, new EntityAIWatchClosest(this, EntityLiving.class, 8.0F));
        this.tasks.addTask(14, new EntityAILookIdle(this));

        this.applyEntityAI();
    }

    public void applyEntityAI() {
    }

    @Override
    public void writeEntityToNBT(NBTTagCompound par1NBTTagCompound)
    {
        super.writeEntityToNBT(par1NBTTagCompound);       
    }
    
    @Override
    public void readEntityFromNBT(NBTTagCompound par1NBTTagCompound)
    {
        super.readEntityFromNBT(par1NBTTagCompound);
    }
    
    @Override
    public EnumActionResult applyPlayerInteraction(EntityPlayer player,	Vec3d vec, @Nullable ItemStack stack, EnumHand hand) {
        if (worldObj.isRemote) {
            player.openGui(HelpingHands.instance, GuiHandler.WORKER_GUI, worldObj, getEntityId(), 0, 0);
        }

    	return super.applyPlayerInteraction(player, vec, stack, hand);
    }

    @Override
    public void onUpdate() {
    	super.onUpdate();
    }

	public void clearTasks()
	{
		
		if(!this.targetTasks.taskEntries.isEmpty())
		{
			for (EntityAITaskEntry t : this.targetTasks.taskEntries) 
			{
				this.targetTasks.removeTask(t.action);
			}
		}
		
	}
	
	public void removeTask(EntityAIBase task)
	{
		if(task != null)
		{
			this.targetTasks.removeTask(task);
			task = null;
		}
	}
	
	@Override
	public void onLivingUpdate() {
		super.onLivingUpdate();
	}
	
	public void moveTo(BlockPos pos, EntityPlayer player, BlockPos facePos) 
	{
		// first clear the move task
		removeTask(aiMoveTo);
		// add task
		this.destinationPos = pos;
		aiMoveTo = new EntityAIMoveTo(this, 1D, 1, pos, facePos);
		this.targetTasks.addTask(50, aiMoveTo);
	}

    public void faceBlock(@Nullable final BlockPos block)
    {
        if (block == null)
        {
            return;
        }

        final double xDifference = block.getX() - this.posX;
        final double zDifference = block.getZ() - this.posZ;
        final double yDifference = block.getY() - (this.posY + (double) this.getEyeHeight());

        final double squareDifference = Math.sqrt(xDifference * xDifference + zDifference * zDifference);
        final double intendedRotationYaw = (Math.atan2(zDifference, xDifference) * 180.0D / Math.PI) - 90.0;
        final double intendedRotationPitch = -(Math.atan2(yDifference, squareDifference) * 180.0D / Math.PI);
        
        float newYaw = (float)intendedRotationYaw;
        float newPitch = (float)intendedRotationPitch;

        this.setLocationAndAngles(this.posX, this.posY, this.posZ, newYaw, newPitch);
        
        final double goToX = xDifference > 0 ? 0.001D : -0.001D;
        final double goToZ = zDifference > 0 ? 0.001D : -0.001D;

        this.moveEntity((float) goToX, 0, (float) goToZ);
    }

    @Override
    public String getName()
    {
    	if(this.hasCustomName())
    		return this.getCustomNameTag();
    	return "";
    }
    
    public void setSelected(boolean selected)
    {
    	this.selected = selected;
    	sendSyncPacket();
    }
    
    public enum EntityTyp
    {
        DEFAULT("default", 0),
        DELIVERY_MAN("deliveryman", 1),
        SOLDIER("soldier",2);

        public final String textureBase;

        public final int numTextures;

        EntityTyp(final String textureBase, final int numTextures)
        {
            this.textureBase = textureBase;
            this.numTextures = numTextures;
        }
        
    }
    
    
    @SideOnly(Side.CLIENT)
    private void spawnParticles(EnumParticleTypes particleType)
    {
        for (int i = 0; i < 5; ++i)
        {
            double d0 = this.rand.nextGaussian() * 0.02D;
            double d1 = this.rand.nextGaussian() * 0.02D;
            double d2 = this.rand.nextGaussian() * 0.02D;
            this.worldObj.spawnParticle(particleType, this.posX + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, this.posY + 1.0D + (double)(this.rand.nextFloat() * this.height), this.posZ + (double)(this.rand.nextFloat() * this.width * 2.0F) - (double)this.width, d0, d1, d2, new int[0]);
        }
    }


    
 // send sync packet to client, if on server side
    public void sendSyncPacket()
    {
    	if (!this.worldObj.isRemote)
    	{
        	try 
        	{
    			HelpingHands.channel.sendToAll(PacketHelpingHands.createEntityPacket(this));
    		} 
        	catch (IOException e) 
        	{
    			e.printStackTrace();
    		}
    	}
    	else
    	{
        	try 
        	{
    			HelpingHands.channel.sendToServer(PacketHelpingHands.createEntityPacket(this));
    		} 
        	catch (IOException e) 
        	{
    			e.printStackTrace();
    		}
    		
    	}
    }


}

 

The inventory class for the entity

Spoiler



package helpinghands.People;

import helpinghands.People.Entities.EntityWorker;

import java.util.Arrays;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;

public class InventoryWorker implements IInventory
{
	// Create and initialize the items variable that will store store the items
	final int NUMBER_OF_SLOTS = 9;
	private ItemStack[] itemStacks = new ItemStack[NUMBER_OF_SLOTS];
	public EntityWorker entity;

    public InventoryWorker(EntityWorker entity)
    {
    	this.entity = entity;
    }

	/* The following are some IInventory methods you are required to override */

	// Gets the number of slots in the inventory
	@Override
	public int getSizeInventory() {
		return itemStacks.length;
		
	}

	// Gets the stack in the given slot
	@Override
	public ItemStack getStackInSlot(int slotIndex) {
		return itemStacks[slotIndex];
	}

	@Override
	public ItemStack decrStackSize(int slotIndex, int count) {
		ItemStack itemStackInSlot = getStackInSlot(slotIndex);
		if (itemStackInSlot == null) return null;

		ItemStack itemStackRemoved;
		if (itemStackInSlot.stackSize <= count) {
			itemStackRemoved = itemStackInSlot;
			setInventorySlotContents(slotIndex, null);
		} else {
			itemStackRemoved = itemStackInSlot.splitStack(count);
			if (itemStackInSlot.stackSize == 0) {
				setInventorySlotContents(slotIndex, null);
			}
		}
	  markDirty();
		return itemStackRemoved;
	}

	// overwrites the stack in the given slotIndex with the given stack
	@Override
	public void setInventorySlotContents(int slotIndex, ItemStack itemstack) {
		itemStacks[slotIndex] = itemstack;
		if (itemstack != null && itemstack.stackSize > getInventoryStackLimit()) {
			itemstack.stackSize = getInventoryStackLimit();
		}
		markDirty();
	}

	@Override
	public int getInventoryStackLimit() {
		return 64;
	}

	@Override
	public boolean isUseableByPlayer(EntityPlayer player) {
		return true;
	}

	@Override
	public boolean isItemValidForSlot(int slotIndex, ItemStack itemstack) {
		return true;
	}

	// set all slots to empty
	@Override
	public void clear() {
		Arrays.fill(itemStacks, null);
	}

	// will add a key for this container to the lang file so we can name it in the GUI
	@Override
	public String getName() {
		return null;
	}

	@Override
	public boolean hasCustomName() {
		return false;
	}

	// standard code to look up what the human-readable name is
	@Override
	public ITextComponent getDisplayName() {
		return this.hasCustomName() ? new TextComponentString(this.getName()) : new TextComponentTranslation(this.getName());
	}

	@Override
	public ItemStack removeStackFromSlot(int slotIndex) {
		ItemStack itemStack = getStackInSlot(slotIndex);
		if (itemStack != null) setInventorySlotContents(slotIndex, null);
		return itemStack;
	}

	@Override
	public void openInventory(EntityPlayer player) {}

	@Override
	public void closeInventory(EntityPlayer player) {}

	@Override
	public int getField(int id) {
		return 0;
	}

	@Override
	public void setField(int id, int value) {}

	@Override
	public int getFieldCount() {
		return 0;
	}

	@Override
	public void markDirty() {
	}

}

 

 

 

 

Link to comment
Share on other sites

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Compared and same.

Meantime i've copied the parts from the hopper container, that also only has 9 slots.

Still not working correctly.

And if i walk over the itemstacks of the inventory (that i have taken from inventory basic, meantime) all stacks are empty.

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.