Jump to content

Close GUI on Block break


aadeg

Recommended Posts

Hi, in my mod I want to do a custom chest. So I create the block, the tileentity, the container and the GUI following the tutorial in the wiki. My problem is that if someone breaks the block (chest) while someone else has the gui of the chest open, the gui doesn't close. This bug can be use to duplicate items because, after the breaking of the chest, the items in it will be droped, but you can either pick up the items in the gui even if the chest is broken.

 

If someone could help, it will be great. Thank you very mush in advance.

Link to comment
Share on other sites

Mh... I still have the problem.

 

In the tile class I put this:

public boolean isUseableByPlayer(EntityPlayer par1EntityPlayer) {
    	return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) == this && par1EntityPlayer.getDistanceSq(this.xCoord + 0.5, this.yCoord + 0.5, this.zCoord + 0.5) < 64;
}

 

And in the Container class i put this, where chest is an instance of the type

public boolean canInteractWith(EntityPlayer par1EntityPlayer){
        return chest.isUseableByPlayer(par1EntityPlayer);
}

 

Link to comment
Share on other sites

For the purposes of simplicity I said that the block is a custom chest, in real is a ChestShop that allow to anyone to buy and sell an item from someone. I wish that this thing doesn't change anything.

 

Here is the Block class

 

 

package it.forgottenworld.blocks;

import java.util.Random;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

import it.forgottenworld.ForgottenItems;
import it.forgottenworld.ForgottenWorld;
import it.forgottenworld.api.blocks.AbstractBlockForgottenContainer;
import it.forgottenworld.tile.TileChestShop;
import it.forgottenworld.utils.BukkitBridge;
import it.forgottenworld.utils.Utils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityChest;
import net.minecraft.util.IIcon;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;

public class BlockChestShop extends BlockForgottenContainerOrientable {

Random random = new Random();
private IIcon icon;

    public BlockChestShop()
    {
        super(Material.wood);
        this.setResistance(10000F);
    }
    
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconReg) {
	this.icon = iconReg.registerIcon(this.getTextureName());
}

    @SideOnly(Side.CLIENT)
    protected String getTextureName() {
        return "minecraft:planks_oak";
    }

    @Override
    public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack itemstack)
    {
        TileEntity tileEntity = world.getTileEntity(x, y, z);
        if (tileEntity != null && tileEntity instanceof TileChestShop && entityliving instanceof EntityPlayer)
        {
            ((TileChestShop) tileEntity).setOwner(((EntityPlayer) entityliving).getGameProfile().getName());
        }

        super.onBlockPlacedBy(world, x, y, z, entityliving, itemstack);

    }

    @Override
    public void breakBlock(World world, int x, int y, int z, Block block, int metadata) {
    	
    	TileChestShop tilechestshop = (TileChestShop)world.getTileEntity(x, y, z);
    	
    	if (tilechestshop != null) {
    		
    		for (int i=0; i<tilechestshop.getSizeInventory(); i++) {
    			
    			ItemStack itemstack = tilechestshop.getStackInSlot(i);

    			if (itemstack != null) {
    				float f = this.random.nextFloat() * 0.8F + 0.1F;
                    float f1 = this.random.nextFloat() * 0.8F + 0.1F;
                    EntityItem entityitem;

                    for (float f2 = this.random.nextFloat() * 0.8F + 0.1F; itemstack.stackSize > 0; world.spawnEntityInWorld(entityitem)) {
                        int j1 = this.random.nextInt(21) + 10;

                        if (j1 > itemstack.stackSize)
                            j1 = itemstack.stackSize;

                        itemstack.stackSize -= j1;
                        entityitem = new EntityItem(world, (double)((float)x + this.random.nextFloat() * 0.8F + 0.1F),
                        		(double)((float)y + this.random.nextFloat() * 0.8F + 0.1F), (double)((float)z + f2),
                        		new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage()));
                        
                        entityitem.motionX = (double)((float)this.random.nextGaussian() * 0.05F);
                        entityitem.motionY = (double)((float)this.random.nextGaussian() * 0.05F + 0.2F);
                        entityitem.motionZ = (double)((float)this.random.nextGaussian() * 0.05F);

                        if (itemstack.hasTagCompound())
                            entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy());
                    }
    			}
    		}
    		System.out.println("money "+tilechestshop.getMoney());
    		if (tilechestshop.getMoney() > 0) {
    			int[] money = BukkitBridge.convertBalanceToMoney(tilechestshop.getMoney());
    			System.out.println(money[3]);
    			for (int meta=0; meta<4; meta++) {
    				while (money[meta] > 64) {
    					EntityItem entityitem = new EntityItem(world, (double)((float)x + this.random.nextFloat() * 0.8F + 0.1F),
    															(double)((float)y + this.random.nextFloat() * 0.8F + 0.1F),
    															(double)((float)z + this.random.nextFloat() * 0.8F + 0.1F),
    															new ItemStack(ForgottenItems.zenar,	64, meta));
    					
                        entityitem.motionX = (double)((float)this.random.nextGaussian() * 0.05F);
                        entityitem.motionY = (double)((float)this.random.nextGaussian() * 0.05F + 0.2F);
                        entityitem.motionZ = (double)((float)this.random.nextGaussian() * 0.05F);
                        
                        money[meta] -= 64;
                        world.spawnEntityInWorld(entityitem);
    				}
    				if (money[meta] > 0) {
    					EntityItem entityitem = new EntityItem( world,
							(double)((float)x + this.random.nextFloat() * 0.8F + 0.1F),
							(double)((float)y + this.random.nextFloat() * 0.8F + 0.1F),
							(double)((float)z + this.random.nextFloat() * 0.8F + 0.1F),
							new ItemStack(ForgottenItems.zenar,	money[meta], meta));
    					
					entityitem.motionX = (double)((float)this.random.nextGaussian() * 0.05F);
					entityitem.motionY = (double)((float)this.random.nextGaussian() * 0.05F + 0.2F);
					entityitem.motionZ = (double)((float)this.random.nextGaussian() * 0.05F);

					world.spawnEntityInWorld(entityitem);
    				}
    			}
    		}
    		
    	}
    	
    	
        super.breakBlock(world, x, y, z, block, metadata);
        world.removeTileEntity(x, y, z);
    }

    @Override
    public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int metadata, float what, float these, float are) {
        TileEntity tileEntity = world.getTileEntity(x, y, z);
        if (tileEntity == null) {
            return false;
        }

        if(player.isSneaking()) {
            player.openGui(ForgottenWorld.instance, Utils.GUICHESTSHOPCONFIG_ID, world, x, y, z);
            return true;
        }
        player.openGui(ForgottenWorld.instance, Utils.GUICHESTSHOP_ID, world, x, y, z);
        return true;
    }
    public TileEntity createTileEntity(World world, int metadata)
    {

        return new TileChestShop();
    }

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

    @Override
    public int getRenderType()
    {
        return -1;
    }

    @Override
    public boolean isOpaqueCube()
    {
        return false;
    }
    
    /**
     * Called when a player removes a block.  This is responsible for
     * actually destroying the block, and the block is intact at time of call.
     * This is called regardless of whether the player can harvest the block or
     * not.
     *
     * Return true if the block is actually destroyed.
     *
     * Note: When used in multiplayer, this is called on both client and
     * server sides!
     *
     * @param world The current world
     * @param player The player damaging the block, may be null
     * @param x X Position
     * @param y Y position
     * @param z Z position
     * @return True if the block is actually destroyed.
     */
    public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z) {
    	TileChestShop tile = (TileChestShop)world.getTileEntity(x, y, z);
        if (tile != null && !tile.canOpenConfig(player))
        	return false;
    	
        return world.setBlockToAir(x, y, z);
    }
}

 

 

 

The Container:

 

 

package it.forgottenworld.inventory;

import it.forgottenworld.ForgottenItems;
import it.forgottenworld.tile.TileChestShop;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.inventory.*;
import net.minecraft.item.ItemStack;
import net.minecraft.village.MerchantRecipe;
import net.minecraft.world.World;

public class ContainerChestShop extends Container {

    public InventoryShop tempInv;
    private World worldObj;
    private int posX;
    private int posY;
    private int posZ;
    private TileChestShop chestShop;
    private static boolean onceFlag = true; // necessaria per dimezzare il numero delle chiamate lato client

    public ContainerChestShop (EntityPlayer par1Player,TileChestShop parChestShop)
    {
        this.tempInv = new InventoryShop(par1Player, parChestShop);
        this.worldObj = parChestShop.getWorldObj();
        this.posX = parChestShop.xCoord;
        this.posY = parChestShop.yCoord;
        this.posZ = parChestShop.zCoord;
        this.chestShop = parChestShop;

        // questa soluzione è orribile
        if (!this.chestShop.getWorldObj().isRemote)
        	parChestShop.openInventory();
        else if (onceFlag) {
        	onceFlag = !onceFlag;
        	parChestShop.openInventory(); // aggiorna i visitors correttamente lato client e controlla il decadimento dei cibi
        }
        else
        	onceFlag = !onceFlag;

        this.addSlotToContainer(new SlotFake(parChestShop.getGood(),12,23));
        this.addSlotToContainer(new SlotShop(par1Player, tempInv, parChestShop, 4, 136, 56));
        
        this.addSlotToContainer(new SlotFake(this.chestShop.getSellRecipe() != null ? (this.chestShop.getSellRecipe().getItemToSell()).setStackDisplayName("Compra per") : null,125,23));
        this.addSlotToContainer(new SlotFake(this.chestShop.getBuyRecipe() != null ? (this.chestShop.getBuyRecipe().getItemToBuy()).setStackDisplayName("Vende per") : null,55,23));
        this.addSlotToContainer(new Slot(tempInv, 0, 21,55));
        this.addSlotToContainer(new Slot(tempInv, 1, 40,55));
        this.addSlotToContainer(new Slot(tempInv, 2, 59,55));
        this.addSlotToContainer(new Slot(tempInv, 3, 78,55));

        int l;
        int i1;


        for (l = 0; l < 3; ++l)
        {
            for (i1 = 0; i1 < 9; ++i1)
            {
                this.addSlotToContainer(new Slot(par1Player.inventory, i1 + l * 9 + 9, 8 + i1 * 18, 84 + l * 18));
            }
        }
        for (l = 0; l < 9; ++l)
        {
            this.addSlotToContainer(new Slot(par1Player.inventory, l, 8 + l * 18, 142));


        }

    }

    public void addCraftingToCrafters(ICrafting par1ICrafting)
    {
        super.addCraftingToCrafters(par1ICrafting);
    }


    /**
     * Looks for changes made in the container, sends them to every listener.
     */
    public void detectAndSendChanges()
    {
        super.detectAndSendChanges();
    }

    /**
     * Callback for when the crafting matrix is changed.
     */
    public void onCraftMatrixChanged(IInventory par1IInventory)
    {
        this.tempInv.resetRecipeAndSlots();
        super.onCraftMatrixChanged(par1IInventory);
    }
    /**
     * Called when the container is closed.
     */
    public void onContainerClosed(EntityPlayer par1EntityPlayer)
    {
        super.onContainerClosed(par1EntityPlayer);

        if (!this.worldObj.isRemote)
        {
            ItemStack itemstack;
            for(int i = 0; i < 4; ++i)
            {
                itemstack = this.tempInv.getStackInSlotOnClosing(i);

                if (itemstack != null)
                {
                    par1EntityPlayer.dropPlayerItemWithRandomChoice(itemstack, false);
                }
            }
        }
    }

    public boolean canInteractWith(EntityPlayer par1EntityPlayer)
    {
        return chestShop.isUseableByPlayer(par1EntityPlayer);
    }

    /**
     * Called when a player shift-clicks on a slot. You must override this or you will crash when someone does that.
     */
    public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int par2)
    {
        ItemStack itemstack = null;
        Slot slot = (Slot)this.inventorySlots.get(par2);

        if (slot != null && slot.getHasStack())
        {
            ItemStack itemstack1 = slot.getStack();
            itemstack = itemstack1.copy();

            if (par2 == 1)
            {

                slot.onSlotChange(itemstack1, itemstack);
            }
            else if (par2 >= 4 && par2 < 33)
            {
                if (!this.mergeItemStack(itemstack1, 34, 43, false))
                {
                    return null;
                }
            }
            else if (par2 >= 34 && par2 < 43)
            {
                if (!this.mergeItemStack(itemstack1, 4, 34, false))
                {
                    return null;
                }
            }
            else if (!this.mergeItemStack(itemstack1, 4, 43, false))
            {
                return null;
            }

            if (itemstack1.stackSize == 0)
            {
                slot.putStack((ItemStack)null);
            }
            else
            {
                slot.onSlotChanged();
            }

            if (itemstack1.stackSize == itemstack.stackSize)
            {
                return null;
            }

            slot.onPickupFromSlot(par1EntityPlayer, itemstack1);
        }

        return itemstack;
    }


}

 

 

 

And the GUI:

 

 

package it.forgottenworld.client.gui;

import it.forgottenworld.client.RenderLibs;
import it.forgottenworld.inventory.ContainerChestShop;
import it.forgottenworld.tile.TileChestShop;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.StatCollector;
import net.minecraft.village.MerchantRecipe;
import net.minecraft.village.MerchantRecipeList;
import org.lwjgl.opengl.GL11;

public class GuiChestShop extends GuiContainer {

    TileChestShop chestShop;
    public GuiChestShop(EntityPlayer par1Player,TileChestShop par2ChestShop)
    {
        super(new ContainerChestShop(par1Player, par2ChestShop));
        chestShop = par2ChestShop;

    }

    final float scale = 0.5F;
    String str;
    @Override
    protected void drawGuiContainerForegroundLayer(int param1, int param2) {

        str = this.chestShop.hasCustomInventoryName() ? this.chestShop.getInventoryName() : StatCollector.translateToLocal(chestShop.getInventoryName()) + " di " + chestShop.getOwner();
        this.fontRendererObj.drawString(str , xSize - this.fontRendererObj.getStringWidth(str) - 5, 5 , 4210752);
        this.mc.renderEngine.bindTexture(new ResourceLocation("forgottenworld:textures/gui/shop.png"));

        if(chestShop.getSellRecipe() != null && chestShop.getSellRecipe() != null && !chestShop.hasGood(chestShop.getGood()))
            this.drawTexturedModalRect(55, 23,176, 42, 15, 15);

        if(chestShop.getBuyRecipe() != null && !chestShop.canAddToInventory(chestShop.getBuyRecipe().getItemToSell()) || this.chestShop.getMoney() < this.chestShop.getSellPrice())
            this.drawTexturedModalRect(125, 23,176, 42, 15, 15);

        GL11.glScalef(scale, scale, scale);

        if(chestShop.getSellRecipe() != null)
        {

            if(chestShop.hasGood(chestShop.getGood()))
            {
                this.fontRendererObj.drawString("PREZZO DI VENDITA" , (63-fontRendererObj.getStringWidth("PREZZO DI VENDITA")/(2*(int)(1/ scale)))*(int)(1/ scale), 40*(int) (1/ scale) , 4210752);
            }
            else
                this.fontRendererObj.drawString("ESAURITO" , (63-fontRendererObj.getStringWidth("ESAURITO")/(2*(int)(1/ scale)))*(int)(1/ scale), 40*(int) (1/ scale) , 4210752);

        }
        if(chestShop.getBuyRecipe() != null)
        {


            if(!chestShop.canAddToInventory(chestShop.getBuyRecipe().getItemToSell()))
                this.fontRendererObj.drawString("SHOP PIENO" ,(133-fontRendererObj.getStringWidth("SHOP PIENO")/(2*(int)(1/ scale)))*(int)(1/ scale), 40 *(int) (1/ scale), 4210752);
            else if(this.chestShop.getMoney() < this.chestShop.getSellPrice())
                this.fontRendererObj.drawString("SOLDI INSUFFICIENTI" ,(133-fontRendererObj.getStringWidth("SOLDI INSUFFICIENTI")/(2*(int)(1/ scale)))*(int)(1/ scale), 40 *(int) (1/ scale), 4210752);
            else
                this.fontRendererObj.drawString("PREZZO D'ACQUISTO" ,(133-fontRendererObj.getStringWidth("PREZZO D'ACQUISTO")/(2*(int)(1/ scale)))*(int)(1/ scale), 40 *(int) (1/ scale), 4210752);

        }
        GL11.glScalef(1 / scale, 1 / scale, 1 / scale);

    }

    @Override
    protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
        //draw your Gui here, only thing you need to change is the path
        GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        this.mc.renderEngine.bindTexture(new ResourceLocation("forgottenworld:textures/gui/shop.png"));
        int x = (width - xSize) / 2;
        int y = (height - ySize) / 2;
        this.drawTexturedModalRect(x, y, 0, 0, xSize, ySize);


            if (((ContainerChestShop)this.inventorySlots).tempInv.getCurrentRecipe() == null )
            {
                GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
                GL11.glDisable(GL11.GL_LIGHTING);
                this.drawTexturedModalRect(this.guiLeft + 99, this.guiTop + 53, 176, 0, 28, 21);
            }

    }
}

 

 

 

(I'm Italian so some messages could be written in Italian)

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



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • https://pastebin.com/VwpAW6PX My game crashes upon launch when trying to implement the Oculus mod to this mod compilation, above is the crash report, I do not know where to begin to attempt to fix this issue and require assistance.
    • https://youtube.com/shorts/gqLTSMymgUg?si=5QOeSvA4TTs-bL46
    • CubeHaven is a SMP server with unique features that can't be found on the majority of other servers! Java: MC.CUBEHAVEN.NET Bedrock: MC.CUBEHAVEN.NET:19132 3 different stores: - CubeHaven Store: Our store to purchase using real money. - Bitcoin Store: Store for Bitcoin. Bitcoin can be earned from playing the server. Giving options for players if they want to spend real money or grind to obtain exclusive packages. - Black Market: A hidden store for trading that operates outside our traditional stores, like custom enchantments, exclusive items and more. Some of our features include: Rank Up: Progress through different ranks to unlock new privileges and perks. 📈 Skills: RPG-style skill system that enhances your gaming experience! 🎮 Leaderboards: Compete and shine! Top players are rewarded weekly! 🏆 Random Teleporter: Travel instantly across different worlds with a click! 🌐 Custom World Generation: Beautifully generated world. 🌍 Dungeons: Explore challenging and rewarding dungeons filled with treasures and monsters. 🏰 Kits: Unlock ranks and gain access to various kits. 🛠️ Fishing Tournament: Compete in a friendly fishing tournament! 🎣 Chat Games: Enjoy games right within the chat! 🎲 Minions: Get some help from your loyal minions. 👥 Piñata Party: Enjoy a festive party with Piñatas! 🎉 Quests: Over 1000 quests that you can complete! 📜 Bounty Hunter: Set a bounty on a player's head. 💰 Tags: Displayed on nametags, in the tab list, and in chat. 🏷️ Coinflip: Bet with other players on coin toss outcomes, victory, or defeat! 🟢 Invisible & Glowing Frames: Hide your frames for a cleaner look or apply a glow to it for a beautiful look. 🔲✨[ Player Warp: Set your own warp points for other players to teleport to. 🌟 Display Shop: Create your own shop and sell to other players! 🛒 Item Skins: Customize your items with unique skins. 🎨 Pets: Your cute loyal companion to follow you wherever you go! 🐾 Cosmetics: Enhance the look of your character with beautiful cosmetics! 💄 XP-Bottle: Store your exp safely in a bottle for later use! 🍶 Chest & Inventory Sorting: Keep your items neatly sorted in your inventory or chest! 📦 Glowing: Stand out from other players with a colorful glow! ✨ Player Particles: Over 100 unique particle effects to show off. 🎇 Portable Inventories: Over virtual inventories with ease. 🧳 And a lot more! Become part of our growing community today! Discord: https://cubehaven.net/discord Java: MC.CUBEHAVEN.NET Bedrock: MC.CUBEHAVEN.NET:19132
    • # Problematic frame: # C [libopenal.so+0x9fb4d] It is always the same issue - this refers to the Linux OS - so your system may prevent Java from working   I am not familiar with Linux - check for similar/related issues  
  • Topics

×
×
  • Create New...

Important Information

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