Jump to content

[1.10.02][SOLVED] onBlockActivated running twice with !world.isRemote check


TrekkieCub314

Recommended Posts

I've got a block where, upon right-clicking it with the right kind of item, is supposed to store one of said item in an internal inventory.  If I right-click it with an empty hand, however, it's supposed to drop the item into the world and clear the internal inventory.  The problem I'm having is when I right-click on the block, the item is immediately ejected from the tile entity.  I tried wrapping the guts of the onBlockActivated in a !world.isRemote check, but that doesn't seem to have helped.  Can anyone see what I might be doing wrong?

 

[spoiler=block]

package com.trekkiecub.oddsandends.blocks;

import java.util.Random;

import javax.annotation.Nullable;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.BlockRenderLayer;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import com.trekkiecub.oddsandends.init.BlockInit;
import com.trekkiecub.oddsandends.init.ItemInit;
import com.trekkiecub.oddsandends.items.Item_HealingCrystal;
import com.trekkiecub.oddsandends.tileentity.TileEntity_Sceptre;
import com.trekkiecub.oddsandends.util.OAE_Func;

public class Block_Sceptre_Top extends Block_BeamPowered implements ITileEntityProvider {
protected static final AxisAlignedBB CACTUS_AABB = new AxisAlignedBB(0.375, 0.0D, 0.375D, 0.625D, .75D, 0.625D);
    protected static final AxisAlignedBB CACTUS_COLLISION_AABB = new AxisAlignedBB(0.375, 0.0D, 0.375D, 0.625D, .75D, 0.625D);
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos)
    {
        return CACTUS_AABB;
    }

    @SideOnly(Side.CLIENT)
    public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World worldIn, BlockPos pos)
    {
        return CACTUS_COLLISION_AABB.offset(pos);
    }
public Block_Sceptre_Top() {
	super(Material.CIRCUITS);
}

@Override
public void breakBlock(World worldIn, BlockPos pos, IBlockState state)
{
	TileEntity tile = worldIn.getTileEntity(pos);
	if (tile != null && tile instanceof TileEntity_Sceptre)
	{
		((TileEntity_Sceptre)tile).dropItems();
	}
}

public boolean isOpaqueCube(IBlockState state)
    {
        return false;
    }

@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, @Nullable ItemStack heldItem, EnumFacing side, float hitX, float hitY, float hitZ)
{
	if (!worldIn.isRemote)
	{
		TileEntity_Sceptre thisTile = (TileEntity_Sceptre) worldIn.getTileEntity(pos);
		if (thisTile != null)
		{
			if (!OAE_Func.isStackEmpty(heldItem))
			{
				if (heldItem.getItem() instanceof Item_HealingCrystal)
				{
					if (thisTile.canAddPartial(heldItem))
					{
						ItemStack remaining = thisTile.mergeStack(heldItem.copy());
						playerIn.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, remaining);
						OAE_Func.chatAtPlayer(playerIn, "Can Add");
						return true;
					}
				}
			}
			else
			{
				thisTile.dropItems();
			}
		}
	}
	return false;
}

    public boolean isFullCube(IBlockState state)
    {
        return false;
    }
    
    @SideOnly(Side.CLIENT)
    public BlockRenderLayer getBlockLayer()
    {
        return BlockRenderLayer.CUTOUT;
    }

    public void neighborChanged(IBlockState state, World worldIn, BlockPos pos, Block blockIn)
    {
        if (!this.canBlockStay(worldIn, pos))
        {
            worldIn.destroyBlock(pos, true);
        }
    }

public boolean canBlockStay(World world, BlockPos pos)
{
	if (world.getBlockState(pos.down()) == BlockInit.sceptre_bottom.getDefaultState())
	{
		return true;
	}
	else
	{
		return false;
	}
}

public Item getItemDropped(IBlockState state, Random rand, int fortune)
    {
        return ItemInit.sceptre;
    }

@Override
public TileEntity createNewTileEntity(World worldIn, int meta) {
	return new TileEntity_Sceptre();
}

}

 

 

[spoiler=tile entity]

package com.trekkiecub.oddsandends.tileentity;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;

import com.trekkiecub.oddsandends.entity.Entity_PowerOrb;
import com.trekkiecub.oddsandends.util.OAE_Func;
import com.trekkiecub.oddsandends.util.Type_CoordEntry;

public class TileEntity_Sceptre extends TileEntity implements IPowerCrystal, ITickable, IInventory {
private List<Type_CoordEntry> sources = new ArrayList<Type_CoordEntry>();
private List<Type_CoordEntry> destinations = new ArrayList<Type_CoordEntry>();
private ItemStack itemStacks[] = new ItemStack[1];
int cooldown = 0;
int maxCooldown = 30;

public void updateEntity()
{
	if (!this.worldObj.isRemote)
	{
		cooldown++;
		cooldown = cooldown%maxCooldown;
		if (cooldown == 0 && destinations.size() != 0)
		{
			BlockPos targetPos;
			for (int i = 0; i < destinations.size(); i++)
			{
				targetPos = destinations.get(i).getBlockPos();
				Entity_PowerOrb entity = new Entity_PowerOrb(this.worldObj, this.pos.getX()+.5, this.pos.getY()+.375, this.pos.getZ()+.5);
				entity.setOrientation(this.worldObj.rand.nextInt(2));
				entity.setThrowableHeading(targetPos.getX() + .5 - entity.posX, targetPos.getY() + .375 - entity.posY, targetPos.getZ() + .5 - entity.posZ, 0.05F, 0);
				this.worldObj.spawnEntityInWorld(entity);
			}
		}
		markDirty();
	}
}

public void doThings(int orientation)
{
	if (orientation == 1)
	{
		Vec3d center = OAE_Func.blockCenter(this.pos);
		EntityItem entity = new EntityItem(worldObj, center.xCoord, center.yCoord, center.zCoord, new ItemStack(Items.APPLE));
		this.worldObj.spawnEntityInWorld(entity);
	}
}

public void dropItems()
{
	if (!this.worldObj.isRemote)
	{
		for (int i = 0; i < this.getInventoryStackLimit(); ++i)
		{
			if (itemStacks[i] != null)
			{
				Vec3d center = OAE_Func.blockCenter(this.pos);
				EntityItem entity = new EntityItem(worldObj, center.xCoord, center.yCoord, center.zCoord, itemStacks[i].copy());
				this.worldObj.spawnEntityInWorld(entity);
				this.setInventorySlotContents(i, null);
			}
		}
	}
}

/* Bringing in new source coordinates
   Possible Actions:
   -- Add source, if it doesn't exist
   -- Remove source, if it's in sources
   -- Move from destinations to sources, to switch flow
 */
@Override
public boolean changeConnections(ItemStack linker)
{
	boolean actionTaken = false;
	// Make sure the linker isn't empty
	if (linker.getTagCompound() != null)
	{
		// Again, make sure linker isn't empty
		if (linker.getTagCompound().hasKey("coords"))
		{
			// Get the coordinates in question
			NBTTagCompound nbt = (NBTTagCompound) linker.getTagCompound().getTag("coords");
			Type_CoordEntry coords = new Type_CoordEntry(nbt);
			// Check if these are our own coordinates
			if (coords != this.getMyCoordEntry())
			{
				TileEntity entity = this.worldObj.getTileEntity(coords.getBlockPos());
				if (entity != null && entity instanceof IPowerCrystal)
				{
					// Check to see if the coordinates supplied are in the destinations
					// Meaning we're switching the flow direction
					if (destinations.contains(coords))
					{
						// Make sure we can switch before we switch
						if (canWeSwitch((IPowerCrystal) entity))
						{
							this.switchCoordFunc(coords);
							((IPowerCrystal)entity).switchCoordFunc(this.getMyCoordEntry());
							actionTaken = true;
						}

					}
					// We've repeated a previous action, so we're now undoing it
					else if (sources.contains(coords))
					{
						this.removeCoords(coords, true);
						((IPowerCrystal)entity).removeCoords(this.getMyCoordEntry(), false);
						actionTaken = true;
					}
					// We don't have these coords anywhere, this is a new connection
					else
					{
						this.addCoords(coords, true);
						((IPowerCrystal)entity).addCoords(this.getMyCoordEntry(), false);
						actionTaken = true;
					}
				}
			}
		}
	}
	return actionTaken;
}
private boolean canWeSwitch(IPowerCrystal entity)
{
	return this.canReceivePower() && entity.canSendPower();
}
@Override
public void switchCoordFunc(Type_CoordEntry coords)
{
	if (this.destinations.contains(coords))
	{
		destinations.remove(coords);
		sources.add(coords);
	}
	else
	{
		sources.remove(coords);
		destinations.add(coords);
	}
}
private Type_CoordEntry getMyCoordEntry()
{
	return new Type_CoordEntry(this.worldObj.provider.getDimension(), this.getPos());
}

public Type_CoordEntry getSourceEntry(int i)
{
	if (i >= 0 && i < sources.size())
	{
		return sources.get(i);
	}
	else
	{
		return null;
	}
}
public Type_CoordEntry getDestEntry(int i)
{
	if (i >= 0 && i < destinations.size())
	{
		return destinations.get(i);
	}
	else
	{
		return null;
	}
}
// On deletion of tile entity, tell all source entries to delete our coordinates
// from their destination lists
// Tell all destination entries to delete our coordinates in the sources list
@Override
public List<String> printInventory()
{
	List<String> inventory = new ArrayList<String>();
	for (int i = 0; i < this.getSizeInventory(); i++)
	{
		if (itemStacks[i] != null)
		{
			String line = "Slot " + i + ": " + itemStacks[i].getDisplayName();
			inventory.add(line);
		}
	}
	return inventory;
}
@Override
public List<String> printConnections()
{
	List<String> connections = new ArrayList<String>();
	if (this.canReceivePower())
	{
		connections.add("Sources:");
		for (Type_CoordEntry entry : sources)
		{
			connections.add(entry.printThis());
		}
	}
	if (this.canSendPower())
	{
		connections.add("Destinations:");
		for (Type_CoordEntry entry : destinations)
		{
			connections.add(entry.printThis());
		}
	}
	return connections;
}
@Override
public boolean canSendPower() {
	return true;
	// false if empty
}
@Override
public boolean canReceivePower() {
	return true;
	// false if empty
}
@Override
public void removeCoords(Type_CoordEntry coords, boolean removeFromSource)
{
	if (removeFromSource)
	{
		sources.remove(coords);
	}
	else
	{
		destinations.remove(coords);
	}
}
@Override
public void addCoords(Type_CoordEntry coords, boolean addToSource)
{
	if (addToSource)
	{
		sources.add(coords);
	}
	else
	{
		destinations.add(coords);
	}
}
//
//  Merge the given item stack with the inventory slots either
//  until the stack is empty or the inventory runs out.
public ItemStack mergeStack(ItemStack stack)
{
	ItemStack returnThisStack = stack.copy();
	for (int i = 0; i < getSizeInventory() && returnThisStack.stackSize > 0; i++)
	{
		// This is the maximum amount we can deposit into each slot
		// based on both this tile entity and the number of items
		// Number of items can't go above the item's max stack size
		// Will never be zero: First is hard-coded, second breaks loop
		int remainingSpace = OAE_Func.getMaxStackToAdd(this, returnThisStack, i);
		if (remainingSpace > 0)
		{
			if (itemStacks[i] == null)
			{
				setInventorySlotContents(i, returnThisStack.splitStack(remainingSpace));
			}
			else if (OAE_Func.canWeStack(itemStacks[i], returnThisStack))
			{
				itemStacks[i].stackSize += remainingSpace;
				returnThisStack.splitStack(remainingSpace);
				markDirty();
			}
		}
	}
	if (returnThisStack.stackSize == 0)
	{
		returnThisStack = null;
	}
	return returnThisStack;
}
@Override
public void readFromNBT(NBTTagCompound compound) {
	super.readFromNBT(compound);

	sources = new ArrayList<Type_CoordEntry>();
	destinations = new ArrayList<Type_CoordEntry>();
	if (compound.hasKey("sources"))
	{
		NBTTagList entryList = (NBTTagList) compound.getTag("sources");
		for (int i = 0; i < entryList.tagCount(); i++)
		{
			NBTTagCompound entryCompound = entryList.getCompoundTagAt(i);
			Type_CoordEntry entry = Type_CoordEntry.readEntryFromNBT(entryCompound);
			sources.add(entry);
		}

		entryList = (NBTTagList) compound.getTag("destinations");
		for (int i = 0; i < entryList.tagCount(); i++)
		{
			NBTTagCompound entryCompound = entryList.getCompoundTagAt(i);
			Type_CoordEntry entry = Type_CoordEntry.readEntryFromNBT(entryCompound);
			destinations.add(entry);
		}
		this.cooldown = compound.getInteger("cooldown");
		entryList = (NBTTagList) compound.getTagList("Items", 10);

		for (int i = 0; i < entryList.tagCount(); i++)
		{
			NBTTagCompound stackTag = entryList.getCompoundTagAt(i);
			int slot = stackTag.getByte("Slot") & 255;
			setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(stackTag));
		}
	}
}

@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound) {
	// Store sources under 'sources'
	NBTTagList entryList = new NBTTagList();
	for (Type_CoordEntry entry : sources)
	{
		NBTTagCompound entryCompound = new NBTTagCompound();
		entry.writeToNBT(entryCompound);
		entryList.appendTag(entryCompound);
	}
	compound.setTag("sources", entryList);
	// Store destinations under 'destinations'
	entryList = new NBTTagList();
	for (Type_CoordEntry entry : destinations)
	{
		NBTTagCompound entryCompound = new NBTTagCompound();
		entry.writeToNBT(entryCompound);
		entryList.appendTag(entryCompound);
	}
	compound.setTag("destinations", entryList);
	compound.setInteger("cooldown", this.cooldown);
	// Store inventory
	NBTTagList tagList = new NBTTagList();
	for (int i = 0; i < getSizeInventory(); i++)
	{
		if (getStackInSlot(i) != null)
		{
			NBTTagCompound slotTag = new NBTTagCompound();
			slotTag.setByte("Slot", (byte)i);
			getStackInSlot(i).writeToNBT(slotTag);
			tagList.appendTag(slotTag);
		}
	}
	compound.setTag("Items", tagList);
	return super.writeToNBT(compound);

}

@Override
public void update() {
	updateEntity();

}

@Override
public String getName() {
	return null;
}

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

@Override
public int getSizeInventory() {
	return itemStacks.length;
}

@Override
public ItemStack getStackInSlot(int slot) {
	if (slot < 0 || slot >= this.getSizeInventory())
	{
		return null;
	}
	return this.itemStacks[slot];
}

public boolean canAddPartial(ItemStack stack)
{
	for (int i = 0; i < getSizeInventory(); i++)
	{
		if (OAE_Func.isStackEmpty(itemStacks[i]))
		{
			return true;
		}
		else if (OAE_Func.getMaxStackToAdd(this, stack, i) > 0)
		{
			return true;
		}
	}
	return false;
}
@Override
public ItemStack decrStackSize(int slot, int amount) {
	ItemStack stack = getStackInSlot(slot);
	if (stack != null)
	{
		if (stack.stackSize <= amount)
		{
			setInventorySlotContents(slot, null);
			this.markDirty();
		}
		else
		{
			stack = stack.splitStack(amount);
			if (stack.stackSize == 0)
			{
				setInventorySlotContents(slot, null);
			}
			this.markDirty();
		}
	}
	return stack;
}

@Override
public ItemStack removeStackFromSlot(int index) {
	ItemStack stack = getStackInSlot(index);
	setInventorySlotContents(index, null);
	return stack;
}

@Override
public void setInventorySlotContents(int index, ItemStack stack) {
	if (index >= 0 && index < this.itemStacks.length)
	{
		ItemStack newStack = null;
		if (!OAE_Func.isStackEmpty(stack))
		{
			newStack = stack.copy();
			if (stack.stackSize > getInventoryStackLimit())
			{
				newStack.stackSize = getInventoryStackLimit();
			}
		}
		itemStacks[index] = newStack;
		this.markDirty();
	}

}

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

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

@Override
public void openInventory(EntityPlayer player) {
	// TODO Auto-generated method stub

}

@Override
public void closeInventory(EntityPlayer player) {
	// TODO Auto-generated method stub

}

@Override
public boolean isItemValidForSlot(int index, ItemStack stack) {
	// TODO Auto-generated method stub
	return false;
}

@Override
public int getField(int id) {
	// TODO Auto-generated method stub
	return 0;
}

@Override
public void setField(int id, int value) {
	// TODO Auto-generated method stub

}

@Override
public int getFieldCount() {
	// TODO Auto-generated method stub
	return 0;
}

@Override
public void clear() {
	// TODO Auto-generated method stub

}
}

 

 

[spoiler=helper functions]

package com.trekkiecub.oddsandends.util;

import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.Vec3i;
import net.minecraft.util.text.TextComponentString;

public class OAE_Func {

public static String truncUL(Object object)
{
	if (object instanceof Block)
	{
		return ((Block) object).getUnlocalizedName().substring(5);
	}
	else
	{
		return ((Item) object).getUnlocalizedName().substring(5);
	}
}

public static void chatAtPlayer(EntityPlayer player, String text)
{
	player.addChatComponentMessage(new TextComponentString(text));
}

public static String printPos(BlockPos pos)
{
	return pos.getX() + ", " + pos.getY() + ", " + pos.getZ();
}

public static Vec3d blockCenter(BlockPos pos)
{
	pos.getX();
	Vec3d returnThis = new Vec3d(pos.getX()+0.5, pos.getY()+0.5, pos.getZ()+0.5);
	return returnThis;
}
public static int getMaxStackToAdd(IInventory inventory, ItemStack stack, int slot)
{
	// Determine whether the inventory stack limit or the stack size is smaller
	int stacksize = 0;
	int slotStackSize = 0;
	if (!isStackEmpty(stack))
	{
		stacksize = stack.stackSize;
	}
	if (slot >= 0 && slot < inventory.getSizeInventory())
	{
		ItemStack stackInSlot = inventory.getStackInSlot(slot);
		if (!isStackEmpty(stackInSlot))
		{
			slotStackSize = stackInSlot.stackSize;
		}
	}
	// Max stack size if slot is empty
	int minBound = Math.min(inventory.getInventoryStackLimit(), stacksize);
	int remainingItemSpace = Math.max(0, minBound - slotStackSize);
	return remainingItemSpace;
}

public static boolean isStackEmpty(ItemStack stack)
{
	return (stack == null || stack.getItem() == null || stack.stackSize <= 0);
}
public static boolean canWeStack(ItemStack one, ItemStack two)
{
	if (one == null || two == null)
	{
		return false;
	}
	else if (one.getItem() == two.getItem())
	{
		if (one.isStackable())
		{
			if (one.getItemDamage() == two.getItemDamage())
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
			return false;
		}
	}
	else
	{
		return false;
	}
}

}

 

 

Link to comment
Share on other sites

  • 4 months later...

Check which hand the method has been called for.

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

Right -- You might not stop it from firing twice, but you can act on only the call from a hand you care about.

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

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.