Jump to content

[solved]IsidedInventory block duplicating items


Jdb100

Recommended Posts

I was able to add to my block ISidedInventory to allow it to hold and insert/extract items however when i try to remove the item from the book it duplicates. So a quick overview of my block; if the player is holding a book well he clicks my block it will remove the book and insert the book into the block. When the block is clicked again well the inventory is full it will remove the item and  spawn an entityItem which is the book into the world. The problem when removing the book by clicking it will duplicate the book if the player has more then 1 of the books in his hand. So for example you have 3 books in your hand and you click on the block(which is empty at this point) this removes a book from your hand and places it in the block so then when you click the block again to retrieve your book it spawns 2 books because that was how many i had after i placed the book. However even though this number is how many you have in your hand after adding the book it is not dependent on how many you have when removing the book so if i had 3 then placed 1 and then threw my 2nd one on the ground then clicked it would still spawn 2.

 

Block Code:

 

package com.jdb.village.blocks;

import java.util.Random;

import com.jdb.village.VillageTech;
import com.jdb.village.handlers.TickHandler;
import com.jdb.village.handlers.Timer;
import com.jdb.village.handlers.TimerEvent;
import com.jdb.village.items.ItemJournal;
import com.jdb.village.tileentity.TileEntityDesk;

import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;

public class BlockDesk extends BlockContainer
{

public BlockDesk(int par1) {
	super(par1, Material.wood);
	this.setHardness(2.0f);
	this.setResistance(5.0f);
	this.setStepSound(soundWoodFootstep);
	// TODO Auto-generated constructor stub
}

@Override
    public boolean onBlockActivated(World world, int i, int j, int k, EntityPlayer entityPlayer, int what, float are, float these, float For)
    {
	if(!world.isRemote && VillageTech.instance.handler.canClick == true)
	{
		TileEntityDesk tileEntityDesk = (TileEntityDesk) world.getBlockTileEntity(i, j, k);
		boolean bookAdded = placeBook(entityPlayer, tileEntityDesk);
		if(bookAdded == true)
		{
			VillageTech.instance.handler.canClick = false;
			return true;
		}
		VillageTech.instance.handler.canClick = false;
		dropSlot(world, i, j, k, 0);
		return true;
	}
        return true;
    }

    @Override
    public void breakBlock(World world, int x, int y, int z, int par5, int par6) {
            dropItems(world, x, y, z);
            super.breakBlock(world, x, y, z, par5, par6);
    }

    private void dropItems(World world, int x, int y, int z){
            Random rand = new Random();

            TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
            
            if(!(tileEntity instanceof IInventory))
            {
            	return;
            }
            IInventory inventory = (IInventory) tileEntity;
            
            for(int i = 0; i < inventory.getSizeInventory(); i++)
            {
            	ItemStack item = inventory.getStackInSlot(i);
            	
            	if((item != null) && (item.stackSize > 0))
            	{
            		float rx = rand.nextFloat() * 0.8F + 0.1F;
                    float ry = rand.nextFloat() * 0.8F + 0.1F;
                    float rz = rand.nextFloat() * 0.8F + 0.1F;
                    
                    EntityItem entityItem = new EntityItem(world, x + rx, y + ry, z + rz, new ItemStack(item.itemID, item.stackSize, item.getItemDamage()));
                    
                    if(item.hasTagCompound())
                    {
                    	entityItem.getEntityItem().setTagCompound((NBTTagCompound)item.getTagCompound().copy());
                    }
                    
                    float factor = 0.05f;
                    entityItem.motionX = (rand.nextGaussian() * factor);
                    entityItem.motionY = (rand.nextGaussian() * factor + 0.2000000029802322D);
                    entityItem.motionZ = (rand.nextGaussian() * factor);
                    world.spawnEntityInWorld(entityItem);
                    item.stackSize = 0;
            	}
            }
    }

    @Override
    public TileEntity createNewTileEntity(World world) {
            return new TileEntityDesk();
    }
    
    public boolean shouldSideBeRendered(IBlockAccess iblockaccess, int i, int j, int k, int l)
    {
    	return false;
    }
    
    public boolean isOpaqueCube()
    {
    	return false;
    }
    
    public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityLivingBase, ItemStack itemStack)
    {
    	int dir = MathHelper.floor_double((double)((entityLivingBase.rotationYaw * 4F) / 360F) + 0.5D) & 3;
        world.setBlockMetadataWithNotify(x, y, z, dir, 0);
    }
    
@Override
public void registerIcons(IconRegister iconRegister)
{
	blockIcon = iconRegister.registerIcon("villagetech:journal");
}

 public void dropSlot(World world, int i, int j, int k, int slot)
 {
    TileEntity tileEntity = world.getBlockTileEntity(i, j, k);
    if (!(tileEntity instanceof IInventory))
    {
      return;
    }

    IInventory inventory = (IInventory)tileEntity;

    ItemStack stuff = inventory.getStackInSlot(slot);
    if ((stuff != null) && (stuff.stackSize > 0))
    {
      EntityItem entityItem = new EntityItem(world, i + 0.5F, j + 1.2F, k + 0.5F, new ItemStack(stuff.itemID, stuff.stackSize, stuff.getItemDamage()));

      if (stuff.hasTagCompound())
      {
        entityItem.getEntityItem().setTagCompound((NBTTagCompound)stuff.getTagCompound().copy());
      }

      entityItem.motionX = 0D;
      entityItem.motionY = 0D;
      entityItem.motionZ = 0D;
      world.spawnEntityInWorld(entityItem);
      stuff.stackSize = 0;
      inventory.setInventorySlotContents(slot, null);
      world.markBlockForUpdate(i, j, k);
    }
 }

 public boolean placeBook(EntityPlayer entityPlayer, TileEntityDesk tileEntityDesk)
 {
	 ItemStack book = entityPlayer.getHeldItem();
	 if(book != null)
	 {
		 Item bookTest = book.getItem();
		 if(bookTest instanceof ItemBook)
		 {
			 int bookReturn = tileEntityDesk.addBook(book);
			 if(bookReturn == 0)
			 {
				 entityPlayer.inventory.mainInventory[entityPlayer.inventory.currentItem] = null;
				 return true;

			 }
			 if(bookReturn > 0)
			 {
				 book.stackSize = bookReturn;
				 entityPlayer.inventory.mainInventory[entityPlayer.inventory.currentItem] = book;
				 return true;
			 }
		 }
	 }
	 return false;
 }
}

 

 

Tile Entity Code:

 

package com.jdb.village.tileentity;

import com.jdb.village.items.ItemJournal;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.ISidedInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBook;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.Packet132TileEntityData;
import net.minecraft.tileentity.TileEntity;

public class TileEntityDesk extends TileEntity implements ISidedInventory
{

public ItemStack[] deskInventory;

public TileEntityDesk()
{
	deskInventory = new ItemStack[1];
}

public Packet getDescriptionPacket() {
        NBTTagCompound nbtTag = new NBTTagCompound();
        NBTTagList tagList = new NBTTagList();
        for(int i = 0; i < deskInventory.length; i ++)
        {
        	ItemStack itemStack = deskInventory[i];
        	if(itemStack != null)
        	{
        		NBTTagCompound tag = new NBTTagCompound();
        		tag.setByte("Slot", (byte) i);
        		itemStack.writeToNBT(tag);
        		tagList.appendTag(tag);
        	}
        }
        nbtTag.setTag("deskInventory", tagList);
        return new Packet132TileEntityData(this.xCoord, this.yCoord, this.zCoord, 1, nbtTag);
        }

        public void onDataPacket(INetworkManager net, Packet132TileEntityData packet) 
        {
        	NBTTagCompound nbtTag = packet.data;
        	
        	NBTTagList tagList = nbtTag.getTagList("deskInventory");
        	deskInventory = new ItemStack[getSizeInventory()];
            for (int i = 0; i < tagList.tagCount(); i++)
            {
              NBTTagCompound tag = (NBTTagCompound)tagList.tagAt(i);
              byte slot = tag.getByte("Slot");
              if ((slot >= 0) && (slot < this.deskInventory.length))
              {
                this.deskInventory[slot] = ItemStack.loadItemStackFromNBT(tag);
              }
            }
        }
        
        @Override
        public void writeToNBT(NBTTagCompound nbt)
        {
           super.writeToNBT(nbt);
           
           NBTTagList tagList = new NBTTagList();
           for(int i = 0; i < deskInventory.length; i++)
           {
        	   ItemStack stack = deskInventory[i];
        	   if(stack != null)
        	   {
        		   NBTTagCompound tag = new NBTTagCompound();
        		   tag.setByte("Slot", (byte) i);
        		   stack.writeToNBT(tag);
        		   tagList.appendTag(tag);
        	   }
           }
        }

        @Override
        public void readFromNBT(NBTTagCompound nbt)
        {
           super.readFromNBT(nbt);
           
           NBTTagList tagList = nbt.getTagList("deskInventory");
           deskInventory = new ItemStack[getSizeInventory()];
           for(int i = 0; i < tagList.tagCount(); i++)
           {
        	   NBTTagCompound tag = (NBTTagCompound) tagList.tagAt(i);
        	   byte slot = tag.getByte("Slot");
        	   if((slot >= 0) && (slot < deskInventory.length))
        	   {
        		   deskInventory[slot] = ItemStack.loadItemStackFromNBT(tag);
        	   }
           }
        }
        
        public boolean hasBook()
        {
        	ItemStack stack = getStackInSlot(0);
        	if(stack != null)
        	{
        		return true;
        	}
        	return false;
        }
        
        public int addBook(ItemStack book)
        {
        	if(book != null)
        	{
        		ItemStack deskBook = getStackInSlot(0);
        		if(deskBook == null && book.stackSize <= getInventoryStackLimit())
        		{
        			setInventorySlotContents(0, book);
        			return 0;
        		}
        		if(deskBook == null && book.stackSize > getInventoryStackLimit())
        		{
        			int bookSize = book.stackSize;
        			book.stackSize = getInventoryStackLimit();
        			setInventorySlotContents(0,book);
        			book.stackSize = bookSize;
        			return book.stackSize - getInventoryStackLimit();
        		}
        		/*
        		if(deskBook != null && book.stackSize <= getInventoryStackLimit() && deskBook.stackSize + book.stackSize <= getInventoryStackLimit())
        		{
        			deskBook.stackSize = deskBook.stackSize + book.stackSize;
        			worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
        			return 0;
        		}
        		if(deskBook != null && deskBook.stackSize > getInventoryStackLimit() && deskBook.stackSize + book.stackSize > getInventoryStackLimit())
        		{
        			int remainder = (deskBook.stackSize + book.stackSize) - getInventoryStackLimit();
        			deskBook.stackSize -= remainder;
        			worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
        			return remainder;
        		}
        		*/
        	}
        	else
    		{
    			setInventorySlotContents(0, book);
    			return 0;
    		}
        	return -1;
        }
        
	@Override
	public int getSizeInventory() {
		return deskInventory.length;
	}

	@Override
	public ItemStack getStackInSlot(int slot) {
		return deskInventory[slot];
	}

	@Override
	public ItemStack decrStackSize(int slot, int amount) {
		ItemStack itemStack = getStackInSlot(slot);

		if(itemStack != null)
		{
			if(itemStack.stackSize <= amount)
			{
				setInventorySlotContents(slot, null);
			}
			else
			{
				itemStack = itemStack.splitStack(amount);
				if(itemStack.stackSize == 0)
				{
					setInventorySlotContents(slot, null);
				}
			}
		}
		return itemStack;
	}

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

	@Override
	public void setInventorySlotContents(int slot, ItemStack itemStack) {
		deskInventory[slot] = itemStack;
		if((itemStack != null) && (itemStack.stackSize > getInventoryStackLimit()))
		{
			itemStack.stackSize = getInventoryStackLimit();
		}

		worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
	}

	@Override
	public String getInvName() {
		return "Desk";
	}

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

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

	@Override
	public boolean isUseableByPlayer(EntityPlayer entityPlayer) {
		return (worldObj.getBlockTileEntity(xCoord, yCoord, zCoord) == this) && (entityPlayer.getDistanceSq(xCoord + 0.5D, yCoord + 0.5D, zCoord + 0.5D) < 64D);
	}

	@Override
	public void openChest() {

	}

	@Override
	public void closeChest() {

	}

	@Override
	public boolean isItemValidForSlot(int slot, ItemStack itemstack) 
	{
		 Item stackitem = itemstack.getItem();
		    if (stackitem != null)
		    {

		      if (slot == 0)
		      {
		        if ((stackitem instanceof ItemBook || stackitem instanceof ItemJournal))
		        {
		          return true;
		        }
		      }
		    }
		    return false;
	}

	@Override
	public int[] getAccessibleSlotsFromSide(int side)
	{
		if(side == 0)
		{
			int[] sides = new int[1];
			sides[0] = 3;
			return sides;
		}
		if(side != 1)
		{
			int[] sides = new int[3];
			sides[0] = 0;
			sides[1] = 1;
			sides[2] = 2;
			return sides;
		}
		return null;
	}

	@Override
	public boolean canInsertItem(int slot, ItemStack itemstack, int side)
	{
	      if (itemstack != null)
	      {
	        Item stackItem = itemstack.getItem();
	        if (stackItem instanceof ItemBook || stackItem instanceof ItemJournal && slot == 0)
	        {
	          return true;
	        }
	      }

	    return false;
	}

	@Override
	public boolean canExtractItem(int slot, ItemStack itemstack, int side) 
	{
		return true;
	}
        
        
}

 

 

edit: added check to see if item in slot was greater then inventory stack limit then set it to stack limit if it was.

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.

Announcements



×
×
  • Create New...

Important Information

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