Jump to content

Update item in gui with inventory


Dombear

Recommended Posts

Hello guys. Sorry for my english and thank you in advance for help.

I've made item with gui that should add sharpness enchantment to the diamond sword. Everything works fine but when i pick up sword it lost enchantments. Also player should lost 5 experience lvls, but it's not working.

 

There's video that shows the problem.

 

Gui:

package dombear.l2Mod.gui.guis;

import java.io.IOException;

import dombear.l2Mod.gui.container.ContainerEWD;
import dombear.l2Mod.gui.inventory.EWDInventory;
import dombear.l2Mod.gui.slot.SlotEWD;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentDamage;
import net.minecraft.init.Items;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fml.relauncher.SideOnly;

public class GuiEWD extends GuiContainer{

private float xSize;
private float ySize;

private static final ResourceLocation iconLocation = new ResourceLocation("l2:textures/gui/container/satable.png");

private final EWDInventory inventory;

public GuiEWD(ContainerEWD containerItem) {
	super(containerItem);
	this.inventory = containerItem.inventory;
        
        this.xSize = 176;
        this.ySize = 166;

    }

@Override
public void onGuiClosed(){
        if (this.mc.thePlayer != null){
        	this.inventorySlots.onContainerClosed(this.mc.thePlayer);
        }
    }


@Override
protected void actionPerformed(GuiButton button) throws IOException {
	if(button.id == 0){
		if(inventory.getStackInSlot(0) != null){
			if(inventory.getStackInSlot(0).getUnlocalizedName().equals(new ItemStack(Items.diamond_sword).getUnlocalizedName())){
				ItemStack sword = inventory.getStackInSlot(0);
				if(Minecraft.getMinecraft().thePlayer.experienceLevel >= 5){
					NBTTagList list;
					if(sword.getEnchantmentTagList() != null){
						list = sword.getEnchantmentTagList();

						for(int i = 0; i < list.tagCount(); i++){
							if(sword.getEnchantmentTagList().getCompoundTagAt(i).hasKey("id")){
								if(sword.getEnchantmentTagList().getCompoundTagAt(i).getShort("id") == 16){


									int lvl = sword.getEnchantmentTagList().getCompoundTagAt(i).getShort("lvl");

									sword.getEnchantmentTagList().removeTag(i);
									sword.addEnchantment(Enchantment.getEnchantmentByID(16), lvl + 1);
									Minecraft.getMinecraft().thePlayer.removeExperienceLevel(5);

									inventory.removeStackFromSlot(0);
									inventory.setInventorySlotContents(0, sword);

									SlotEWD slot = (SlotEWD) this.inventorySlots.getSlot(0);
									slot.putStack(sword);	
								}
							}					
						}
					} else {
						sword.addEnchantment(Enchantment.getEnchantmentByID(16), 1);
						Minecraft.getMinecraft().thePlayer.removeExperienceLevel(5);
						inventory.removeStackFromSlot(0);
						inventory.setInventorySlotContents(0, sword);
					}
				}
			}
		}
	}
}


@Override
public void initGui() {
	super.initGui();
	this.buttonList.clear();
        this.buttonList.add(new GuiButton(0, this.guiLeft + 110, this.guiTop + 32, 50, 20, "Enchant"));
}


@Override
    protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
	GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f);
    this.mc.getTextureManager().bindTexture(new ResourceLocation("l2:textures/gui/container/satable.png"));
    this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, (int) this.xSize, (int) this.ySize);
}



@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
	String s = inventory.getDisplayName().getUnformattedText();
    this.fontRendererObj.drawString(s, 88 - this.fontRendererObj.getStringWidth(s) / 2, 6, 4210752);            //#404040
    this.fontRendererObj.drawString("Inventory", 8, 72, 4210752);      //#404040
}

}

 

Container:

package dombear.l2Mod.gui.container;

import dombear.l2Mod.gui.inventory.EWDInventory;
import dombear.l2Mod.gui.slot.SlotEWD;
import dombear.l2Mod.items.ItemEwd;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextComponentString;

public class ContainerEWD extends Container{

public final EWDInventory inventory;

private static final int INV_START = EWDInventory.INV_SIZE, INV_END = INV_START+26,
		HOTBAR_START = INV_END+1, HOTBAR_END = HOTBAR_START+8;

public ContainerEWD(InventoryPlayer playerInv, EWDInventory EWDInventory) {

	this.inventory = EWDInventory;
	// Slot 0
    this.addSlotToContainer(new SlotEWD(this.inventory, 0, 80, 35));
    


    // Player Inventory, Slot 9-35, Slot IDs 9-35
    for (int y = 0; y < 3; ++y) {
        for (int x = 0; x < 9; ++x) {
            this.addSlotToContainer(new Slot(playerInv, x + y * 9 + 9, 8 + x * 18, 84 + y * 18)); 
        }
    }

    // Player Inventory, Slot 0-8, Slot IDs 36-44
    for (int x = 0; x < 9; ++x) {
        this.addSlotToContainer(new Slot(playerInv, x, 8 + x * 18, 142));
    }
    
    
}

@Override
public boolean canInteractWith(EntityPlayer player){
	return inventory.isUseableByPlayer(player);
}


@Override
public ItemStack transferStackInSlot(EntityPlayer par1EntityPlayer, int index){
	ItemStack itemstack = null;
	Slot slot = (Slot) this.inventorySlots.get(index);

	Minecraft.getMinecraft().thePlayer.addChatComponentMessage(new TextComponentString("slot: " + slot.getStack().getDisplayName()));

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

		// If item is in our custom Inventory or armor slot
		if (index < INV_START)
		{
			// try to place in player inventory / action bar
			if (!this.mergeItemStack(itemstack1, INV_START, HOTBAR_END+1, true))
			{
				return null;
			}

			slot.onSlotChange(itemstack1, itemstack);
		}
		// Item is in inventory / hotbar, try to place in custom inventory or armor slots
		else
		{

			// Check that the item is the right type
			if (itemstack1.getItem() instanceof ItemEwd)
			{
				// Try to merge into your custom inventory slots
				// We use 'InventoryItem.INV_SIZE' instead of INV_START just in case
				// you also add armor or other custom slots
				if (!this.mergeItemStack(itemstack1, 0, inventory.INV_SIZE, false))
				{
					return null;
				}
			}
			if (index >= INV_START)
			{
				// place in custom inventory
				if (!this.mergeItemStack(itemstack1, 0, INV_START, 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;
}
@Override
protected boolean mergeItemStack(ItemStack stack, int start, int end, boolean backwards){
	boolean flag1 = false;
	int k = (backwards ? end - 1 : start);
	Slot slot;
	ItemStack itemstack1;

	if (stack.isStackable())
	{
		while (stack.stackSize > 0 && (!backwards && k < end || backwards && k >= start))
		{
			slot = (Slot) inventorySlots.get(k);
			itemstack1 = slot.getStack();

			if (!slot.isItemValid(stack)) {
				k += (backwards ? -1 : 1);
				continue;
			}

			if (itemstack1 != null && itemstack1.getItem() == stack.getItem() &&
					(!stack.getHasSubtypes() || stack.getItemDamage() == itemstack1.getItemDamage()) && ItemStack.areItemStackTagsEqual(stack, itemstack1))
			{
				int l = itemstack1.stackSize + stack.stackSize;

				if (l <= stack.getMaxStackSize() && l <= slot.getSlotStackLimit()) {
					stack.stackSize = 0;
					itemstack1.stackSize = l;
					inventory.markDirty();
					flag1 = true;
				} else if (itemstack1.stackSize < stack.getMaxStackSize() && l < slot.getSlotStackLimit()) {
					stack.stackSize -= stack.getMaxStackSize() - itemstack1.stackSize;
					itemstack1.stackSize = stack.getMaxStackSize();
					inventory.markDirty();
					flag1 = true;
				}
			}

			k += (backwards ? -1 : 1);
		}
	}
	if (stack.stackSize > 0)
	{
		k = (backwards ? end - 1 : start);
		while (!backwards && k < end || backwards && k >= start) {
			slot = (Slot) inventorySlots.get(k);
			itemstack1 = slot.getStack();

			if (!slot.isItemValid(stack)) {
				k += (backwards ? -1 : 1);
				continue;
			}

			if (itemstack1 == null) {
				int l = stack.stackSize;
				if (l <= slot.getSlotStackLimit()) {
					slot.putStack(stack.copy());
					stack.stackSize = 0;
					inventory.markDirty();
					flag1 = true;
					break;
				} else {
					putStackInSlot(k, new ItemStack(stack.getItem(), slot.getSlotStackLimit(), stack.getItemDamage()));
					stack.stackSize -= slot.getSlotStackLimit();
					inventory.markDirty();
					flag1 = true;
				}
			}

			k += (backwards ? -1 : 1);
		}
	}

	return flag1;
}


@Override
public void onContainerClosed(EntityPlayer player)
    {
        InventoryPlayer inventoryplayer = player.inventory;

        if (inventoryplayer.getItemStack() != null)
        {
            player.dropPlayerItemWithRandomChoice(inventoryplayer.getItemStack(), false);
            inventoryplayer.setItemStack((ItemStack)null);
        }
        if(this.inventory.getStackInSlot(0) != null && !player.getEntityWorld().isRemote){
        	EntityItem entityitem = new EntityItem(player.worldObj, player.posX, player.posY+1, player.posZ, this.inventory.getStackInSlot(0));
    		entityitem.setPickupDelay(30);
    		player.worldObj.spawnEntityInWorld(entityitem);	
        }
        
    }
}

 

Slot:

package dombear.l2Mod.gui.slot;

import dombear.l2Mod.items.ItemEwd;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;

public class SlotEWD extends Slot{

public SlotEWD(IInventory inventoryIn, int index, int xPosition, int yPosition) {
	super(inventoryIn, index, xPosition, yPosition);
}

@Override
public boolean isItemValid(ItemStack itemstack)
{
	return (!(itemstack.getItem() instanceof ItemEwd) && itemstack.getUnlocalizedName().contains("sword"));
}
}

 

Inventory:

package dombear.l2Mod.gui.inventory;

import dombear.l2Mod.items.ItemEwd;
import net.minecraft.client.Minecraft;
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.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.common.util.Constants;

public class EWDInventory implements IInventory{

private String name = "Enchant Weapon Diamond-Grade";

private ItemStack invItem;

public static final int INV_SIZE = 1;

private ItemStack[] inventory = new ItemStack[iNV_SIZE];

public EWDInventory(ItemStack stack){
	invItem = stack;
}

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

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

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


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


@Override
public boolean hasCustomName() {
	return name.length() > 0;		
}

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

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

@Override
public void markDirty(){
	for (int i = 0; i < getSizeInventory(); ++i)
	{
		if (getStackInSlot(i) != null && getStackInSlot(i).stackSize == 0) {
			inventory[i] = null;
		}
	}
}

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

@Override
public boolean isItemValidForSlot(int slot, ItemStack itemstack){
	return (!(itemstack.getItem() instanceof ItemEwd) && itemstack.getUnlocalizedName().contains("sword"));
}

@Override
public ITextComponent getDisplayName() {
	return new TextComponentString(name);
}

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

}

@Override
public ItemStack removeStackFromSlot(int index) {
	inventory[index] = null;
	return null;
}

@Override
public void openInventory(EntityPlayer player) {

}


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

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

@Override
public void closeInventory(EntityPlayer player) {
}

@Override
public void clear() {
	this.setInventorySlotContents(0,null);
}

}

Link to comment
Share on other sites

Thank you. I know how to get player and playerInventory, but how can I get item inventory from packet?

 

Edit: I made this, but minecraft is crashing when I press the button.

 

Message:

package dombear.l2Mod.packets;

import dombear.l2Mod.gui.inventory.EWDInventory;
import io.netty.buffer.ByteBuf;
import net.minecraft.inventory.IInventory;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;

public class EWDPacket implements IMessage{

private EWDInventory inventory;

public EWDPacket(EWDInventory inventory){
	this.inventory = inventory;
}

public EWDInventory getInventory() {
	return inventory;
}

@Override
public void fromBytes(ByteBuf buf) {

}

@Override
public void toBytes(ByteBuf buf) {

}

}

 

Handler:

package dombear.l2Mod.packets;

import dombear.l2Mod.gui.inventory.EWDInventory;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;

public class L2PacketHandler implements IMessageHandler<EWDPacket, EWDPacket>{

@Override
public EWDPacket onMessage(EWDPacket message, MessageContext ctx) {

	EntityPlayer player = ctx.getServerHandler().playerEntity;
	InventoryPlayer inventoryPlayer = player.inventory;
	EWDInventory inventory = message.getInventory();


	if(inventory.getStackInSlot(0) != null){
		if(inventory.getStackInSlot(0).getUnlocalizedName().equals(new ItemStack(Items.diamond_sword).getUnlocalizedName())){
			ItemStack sword = inventory.getStackInSlot(0);
			if(player.experienceLevel >= 5){

				NBTTagList list;
				if(sword.getEnchantmentTagList() != null){
					list = sword.getEnchantmentTagList();

					for(int i = 0; i < list.tagCount(); i++){
						if(sword.getEnchantmentTagList().getCompoundTagAt(i).hasKey("id")){
							if(sword.getEnchantmentTagList().getCompoundTagAt(i).getShort("id") == 16){


								int lvl = sword.getEnchantmentTagList().getCompoundTagAt(i).getShort("lvl");

								sword.getEnchantmentTagList().removeTag(i);
								sword.addEnchantment(Enchantment.getEnchantmentByID(16), lvl + 1);
								player.removeExperienceLevel(5);

								inventory.setInventorySlotContents(0, sword);
							}
						}					
					}
				} else {
					sword.addEnchantment(Enchantment.getEnchantmentByID(16), 1);
					player.removeExperienceLevel(5);

					inventory.setInventorySlotContents(0, sword);
				}

			}
		}
	}

	return null;
}


}

Link to comment
Share on other sites

Post the crash log.

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

Two things:

 

1. Your message class must have an empty constructor

 

2. In your message handler, 'EWDInventory inventory = message.getInventory();' is completely pointless, as you don't actually send any data. You have to implement IMessage#toBytes and IMessage#fromBytes to send and receive data. However, in your particular case, you may not need to send any data at all other than the base packet as you can snag the inventory from player.openContainer.

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.