Jump to content

Recommended Posts

Posted

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);
}

}

Posted

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;
}


}

Posted

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.

Posted

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.

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

    • I need to know what mod is doing this crash, i mean the mod xenon is doing the crash but i want to know who mod is incompatible with xenon, but please i need to know a solution if i need to replace xenon, i cant use optifine anymore and all the other mods i tried(sodium, lithium, vulkan, etc) doesn't work, it crash the game.
    • I have been trying to solve a consistent crashing issue on my brother's computer where it will crash during the "Scanning Mod Candidates" phase of the loading process that starts when you click the play button on the Minecraft launcher. The issue seems to stem from a missing library that it mentions in the log file I provide below. I might I'm missing the bigger issue here for a smaller one but hopefully someone can find what I'm missing. Here's all of the stuff that I've been able to figure out so far: 1. It has nothing to do with mods, the crash happened with a real modpack, and even when I made a custom modpack and launched it without putting ANY mods into it (That is where the log file comes from by the way). 2. I have tried to find this class like a file in the Minecraft folders, but I've had no luck finding it (I don't think it works like that, but since I really don't understand how it works, I just figured I'd try). 3. I haven't seen anyone else have this issue before. 4. I know that my modpack (with mods) does work since I've run it on my computer, and it works fantastic. For some reason my brother's computer can't seem to run anything through curseforge. 5. This is for Minecraft version 1.20.1, Minecraft launcher version 3.4.50-2.1.3, forge 47.3.0, and curseforge app version 1.256.0.21056 6. My brother is using a Dell laptop from 6 years ago running Windows 10 (If you think more info on this would help, please ask as I do have it. I'm just choosing not to put it here for now). 7. I have reinstalled the curseforge app and installed Minecraft version 1.20.1. I have not reinstalled Minecraft or forge 47.3.0 but I didn't know if that would help. 8. I had an error code of 1 Please let me know if there is anything else that I am missing that you would like me to add to this post/add in a comment! Lastly, many thanks in advance to whoever can help! ------------- LOG FILE (latest.log) ------------- (from /Users/<NAME OF USER>/cursforge/minecraft/Instances/<THE NAME OF MY EMPTY MODPACK>/logs/latest.log) (This was made after running an empty modpack with same versions for all apps) ("[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/hxXvGGEK ------------- DEBUG.LOG (I realized that I should have put this here first after I had done all of the work on putting latest.log in) -------------------- (again, "[REDACTED]" is not the actual text from the log, it is me replacing text I figured wouldn't be necessary for fixing and would hurt my privacy) https://pastebin.com/Fmh8GHYs
    • Pastebin... https://pastebin.com/Y3iZ85L5   Brand new profile, does not point to a mod as far as I can tell, my fatal message just has something about mixins. Don't know much about reading logs like this, but am genuinely stuck, please help. Java updated, pc restarted.
    • Fastfund recovery helps an individual to get back their scammed funds irrespective of nationality, Romance scam funds and Broker's scam, all kinds of scam funds are 100% accurately recovered without disappointment, their goal is to give all those who seek help to recover lost satisfaction of funds recovery within 72 hours After countless hours of research and desperate attempts to find a solution, I stumbled upon FASTFUND RECOVERY. It was like finding an oasis in the middle of a desert. Their website promised to help victims of scams reclaim what was rightfully theirs, and I instantly knew I had to give them a shot. Before diving headfirst into the recovery process, I wanted to make sure that FASTFUND RECOVERY was the real deal. So, I did my due diligence and looked into their expertise and reputation. To my relief, I found that they had an impeccable track record, successfully assisting countless individuals in recovering their lost funds. Their team consisted of experts in cybersecurity and financial fraud, armed with the knowledge and tools needed to tackle even the most intricate scams. With their reputation preceding them, I felt a renewed sense of hope. FASTFUND RECOVERY successfully came to my aid and got back the amount I lost to these scammers and for this, I am sending this article for clarification. The info of FASTFUND RECOVERY is email: Fastfundrecovery8 (@)Gmail (.) com. Web fastfundrecovery(.)com. (W/A 1 807/500/7554)
  • Topics

×
×
  • Create New...

Important Information

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