Jump to content

[1.7.10] Gui setting variable in Tile Entity?


robertcars

Recommended Posts

So I am trying to have my GUI set a integer in the tile entity. I was told I would have to do it with packets so that's what im trying to do however i'm new to packets. I do not know how to get the packet to the tile entity I am pretty sure I made the packet and am sending the integer from the GUI to it correctly. Some help would be much appreciated. Thanks in advance.

 

The integer i'm trying to set is id.

 

Tileentity

package com.robert.instaport.common.tileentity;

import com.robert.instaport.Instaport;
import com.robert.instaport.packet.TutorialMessage;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.Packet;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;

public class TileEntityTeleporter extends TileEntity implements IInventory {

        private ItemStack[] inv;

        
    	public int id;

	public TileEntityTeleporter(){
                inv = new ItemStack[1];
        }
        
        @Override
        public int getSizeInventory() {
                return inv.length;
        }

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

        @Override
        public Packet getDescriptionPacket()
        {
        	NBTTagCompound tagCompound = new NBTTagCompound();
        	this.writeToNBT(tagCompound);
        	return new S35PacketUpdateTileEntity(this.xCoord, this.yCoord, this.zCoord, 1, tagCompound);
        }

        @Override
        public void onDataPacket(NetworkManager net, S35PacketUpdateTileEntity pkt)
        {
        	readFromNBT(pkt.func_148857_g());
        	worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
        }
        
        @Override
        public void setInventorySlotContents(int slot, ItemStack stack) {
                inv[slot] = stack;
                if (stack != null && stack.stackSize > getInventoryStackLimit()) {
                        stack.stackSize = getInventoryStackLimit();
                }
        }

        @Override
        public ItemStack decrStackSize(int slot, int amt) {
                ItemStack stack = getStackInSlot(slot);
                if (stack != null) {
                        if (stack.stackSize <= amt) {
                                setInventorySlotContents(slot, null);
                        } else {
                                stack = stack.splitStack(amt);
                                if (stack.stackSize == 0) {
                                        setInventorySlotContents(slot, null);
                                }
                        }
                }
                return stack;
        }

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

        @Override
        public boolean isUseableByPlayer(EntityPlayer player) {
                return worldObj.getTileEntity(xCoord, yCoord, zCoord) == this &&
                player.getDistanceSq(xCoord + 0.5, yCoord + 0.5, zCoord + 0.5) < 64;
        }
        
        @Override
        public void readFromNBT(NBTTagCompound tagCompound) {
                super.readFromNBT(tagCompound);
                NBTTagList tagList = tagCompound.getTagList("Inventory", 10);
                for (int i = 0; i < tagList.tagCount(); i++) {
                        NBTTagCompound tag = (NBTTagCompound) tagList.getCompoundTagAt(i);
                        byte slot = tag.getByte("Slot");
                        if (slot >= 0 && slot < inv.length) {
                                inv[slot] = ItemStack.loadItemStackFromNBT(tag);
                        }
                }
                
                setId(tagCompound.getInteger("ids"));
        }
        TutorialMessage mes;
        @Override
        public void writeToNBT(NBTTagCompound tagCompound) {
                super.writeToNBT(tagCompound);
                
                NBTTagList itemList = new NBTTagList();
                for (int i = 0; i < inv.length; i++) {
                        ItemStack stack = inv[i];
                        if (stack != null) {
                                NBTTagCompound tag = new NBTTagCompound();
                                tag.setByte("Slot", (byte) i);
                                stack.writeToNBT(tag);
                                itemList.appendTag(tag);
                        }
                }
                tagCompound.setTag("Inventory", itemList);

                tagCompound.setInteger("ids", getId());
                System.out.println("ID: " + Instaport.snw.getPacketFrom(new TutorialMessage()));
        }
        
        public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
        
	@Override
	public String getInventoryName() {
		return null;
	}

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

	@Override
	public void openInventory() {					
	}

	@Override
	public void closeInventory() {
	}

	@Override
	public boolean isItemValidForSlot(int p_94041_1_, ItemStack p_94041_2_) {
		return false;
	}
}

 

Gui

package com.robert.instaport.gui;

import io.netty.buffer.ByteBuf;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.network.play.server.S35PacketUpdateTileEntity;
import net.minecraft.util.ResourceLocation;

import org.lwjgl.opengl.GL11;

import com.robert.instaport.Instaport;
import com.robert.instaport.common.container.ContainerTeleporter;
import com.robert.instaport.common.tileentity.TileEntityTeleporter;
import com.robert.instaport.lib.Reference;
import com.robert.instaport.packet.TutorialMessage;

public class GuiTeleporter extends GuiContainer {

	public final int xSizeOfTexture = 176;
	public final int ySizeOfTexture = 228;

	private GuiTextField idField;

	public int id;

	@SuppressWarnings("unused")
	private TileEntityTeleporter tileEntityKeyPad;
	private TileEntityTeleporter tileEntityTeleporter = new TileEntityTeleporter();

        public GuiTeleporter (InventoryPlayer inventoryPlayer, TileEntityTeleporter tileEntity) {
                //the container is instanciated and passed to the superclass for handling
                super(new ContainerTeleporter(inventoryPlayer, tileEntity));
                tileEntityTeleporter = tileEntity;
                this.xSize = xSizeOfTexture;
                this.ySize = ySizeOfTexture;
                TileEntityTeleporter tile = (TileEntityTeleporter) tileEntityTeleporter.getWorldObj().getTileEntity(tileEntityTeleporter.xCoord, tileEntityTeleporter.yCoord, tileEntityTeleporter.zCoord);
                id = tile.getId();
        }

        @Override
        protected void drawGuiContainerForegroundLayer(int param1, int param2) {
        		String title = "Teleporter";
                fontRendererObj.drawString(title, 7, ySize - 220, 4210752);
                fontRendererObj.drawString("Security Card:", 7, ySize - 118, 4210752);
        }
        
        @SuppressWarnings("unchecked")
	@Override
        public void initGui() {
                super.initGui();
                
                //make buttons
                buttonList.add(new GuiButton(1, width / 2 - 20 / 2 - 60, this.height / 2 - 65, 20, 20, "+"));
                buttonList.add(new GuiButton(2, width / 2 - 20 / 2 + 60, this.height / 2 - 65, 20, 20, "-"));
                buttonList.add(new GuiButton(3, width / 2 - 100 / 2, this.height / 2 - 35, 100, 20, "Save"));

                idField = new GuiTextField(fontRendererObj, this.width / 2 - 70 / 2, this.height / 2 - 65, 70, 20);
                idField.setFocused(false);
                idField.setMaxStringLength(10);
        }
        
        public void updateScreen() {
        	idField.setText(Integer.toString(id));
        }
        
        public void drawScreen(int i, int j, float f) {
        	super.drawScreen(i, j, f);
        	idField.drawTextBox();

        }
        ByteArrayOutputStream bos = new ByteArrayOutputStream(;
        DataOutputStream outputStream = new DataOutputStream(bos);

        protected void actionPerformed(GuiButton guibutton) {
            TileEntityTeleporter tile = (TileEntityTeleporter) tileEntityTeleporter.getWorldObj().getTileEntity(tileEntityTeleporter.xCoord, tileEntityTeleporter.yCoord, tileEntityTeleporter.zCoord);
            switch(guibutton.id) {
                case 1://add
                	id += 1;
                    break;
                case 2:// subtract
                	if(!(id <= 0)) id -= 1;
                	break;
                case 3://save
                	Instaport.snw.sendToServer(new TutorialMessage(id));
            	}
                //Packet code here
                //PacketDispatcher.sendPacketToServer(packet); //send packet
        }

        ResourceLocation texture = new ResourceLocation(Reference.MOD_ID.toLowerCase() + ":" + "textures/gui/Teleporter.png");
        @Override
        protected void drawGuiContainerBackgroundLayer(float par1, int par2, int par3) {
        		
                GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
                //this.mc.renderEngine.bindTexture(texture);
                this.mc.getTextureManager().bindTexture(texture);
                int x = (width - xSizeOfTexture) / 2;
                int y = (height - ySizeOfTexture) / 2;
                this.drawTexturedModalRect(x, y, 0, 0, xSizeOfTexture, ySizeOfTexture);
        }

}

 

PacketHandler

package com.robert.instaport.packet;

import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;

public class TutorialMessageHandler implements IMessageHandler<TutorialMessage, IMessage> { 

    @Override
    public IMessage onMessage(TutorialMessage message, MessageContext ctx) { 
        System.out.println(message.extremelyImportantInteger);
        return null;
    }

}

 

Packet

package com.robert.instaport.packet;

import io.netty.buffer.ByteBuf;
import cpw.mods.fml.common.network.simpleimpl.IMessage;

public class TutorialMessage implements IMessage{
    public int extremelyImportantInteger; 

    public TutorialMessage() {}

    public TutorialMessage(int a) { 
        this.extremelyImportantInteger = a;
    }

    @Override
    public void toBytes(ByteBuf buf) { 
        buf.writeInt(extremelyImportantInteger);
    }

    @Override
    public void fromBytes(ByteBuf buf) { 
        this.extremelyImportantInteger = buf.readInt();
    }

}

Link to comment
Share on other sites

On the server get the player's currently open Container (player.openContainer). That points to your Container (check that is does, clients can send incorrect data!) and you can get the TileEntity from there.

Would I have to add some type of class for the server or would that go in the gui or tile entity?

Link to comment
Share on other sites

I think he's just a little confused. I will assume (and I hope I'm correct) that your packet is registered for SERVER (GUIs are client side so only natural to receive those packets on the server)

 

Your packet is what is loaded and sent from the client (modname.<instance of your network channel>.sendToServer(new MyMessage("information")))

this would be called or used in the GUI

 

now your packetHandler (which is what the server is using) is listening for all packets of "MyMessage" (or in my mind it is) and it has one function "onMessage"

This is where the packet is received, and what everyone is saying

You do it when the packet is received.

Is them saying "Inside your 'onMessage' method inside your handler extract the information from the passed 'MyMessage'"

 

Just look at the example from the tutorial mainly

System.out.println(String.format("Received %s from %s", 
				message.text, 
				ctx.getServerHandler().playerEntity.getDisplayName()));
		return null;

 

the example 'message' has a public String text; field so that is why in the string format 'message.text' is being used as the first index. However yours you would probably have:

 

MyMessage (int x, int, y, int z, int value)

{

this. x = x;

this.y = y;

this.z = z;

this.value = value;

}

 

and your handler will find the world from the player and from the world the tileEntity

te = (yourTileEntity)ctx.getServerHandler().playerEntity.getEntityWorld().getTileEntity(MyMessage.x, MyMessage.y, MyMessage.z);

te.valueHolder = MyMessage.value;

 

that's the basic idea you might also want to throw other things into it like catching for nulls or what have you. Hopefully this has increased your understanding of how it works if not then I failed horribly.

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.