老实说我已经忘了这个mod是怎么写出来的了。

所以下面的代码不能运行是非常正常的。

 

上回书说到,我们处理了玩家拿着背包右键时触发的事件,发送了一条打开背包窗口的命令,但是背包窗口还没有写,这回就来解决这个问题。

这次因为嵌套关系太多,所以我按执行顺序反过来说。

那么先不管上次没有打开的那个GUI。

 

MC中的每一个能放进物品的容器,不管是箱子、熔炉还是酿造台,各自都持有一个自己的内容空间(Inventory)实例,在这个内容空间中各自保存自己的内容物。

内容空间的基类是InventoryBasic,实现了IInventory接口,为了方便,咱直接继承InventoryBasic类。

InventoryBasic类已经实现了大部分内容空间需要的功能,可以粗读一下代码,挺好懂的。

于是我们黑猫背包的内容空间类只需要处理内容物的保存和读取。

 1 public class InventoryKuroNeko extends InventoryBasic {
 2     public static final String TITLE = "黑猫";
 3     public static final int SLOTS_PER_LINE = 9;
 4     public static final int LINES = 2;
 5     
 6     private ItemStack itemStack;
 7     
 8     private String id;
 9     
10     public InventoryKuroNeko(ItemStack itemStack) {
11         super(TITLE, true, LINES * SLOTS_PER_LINE);
12         
13         this.itemStack = itemStack;
14         
15         if (!itemStack.hasTagCompound()) {
16             itemStack.setTagCompound(new NBTTagCompound());
17             id = UUID.randomUUID().toString();
18         }
19         
20         readFromNBT(itemStack.getTagCompound());
21     }
22     
23     public NBTTagCompound writeToNBT(NBTTagCompound compound) {
24         NBTTagList items = new NBTTagList();
25         
26         for (int i = 0; i < getSizeInventory(); i++) {
27             ItemStack itemStack = getStackInSlot(i);
28             if (itemStack != null) {
29                 NBTTagCompound item = new NBTTagCompound();
30                 item.setInteger("slot", i);
31                 itemStack.writeToNBT(item);
32                 items.appendTag(item);
33             }
34         }
35         
36         compound.setTag("items", items);
37         
38         compound.setString("id", id);
39         
40         return compound;
41     }
42     
43     public void readFromNBT(NBTTagCompound compound) {
44         if (id == null) {
45             id = compound.getString("id");
46         }
47         if (id == null) {
48             id = UUID.randomUUID().toString();
49         }
50         
51         NBTTagList items = compound.getTagList("items", 10);
52         
53         for (int i = 0; i < items.tagCount(); i++) {
54             NBTTagCompound item = items.getCompoundTagAt(i);
55             
56             int slot = item.getInteger("slot");
57             if (slot >= 0 && slot < getSizeInventory()) {
58                 ItemStack itemStack = ItemStack.loadItemStackFromNBT(item);
59                 setInventorySlotContents(slot, itemStack);
60             }
61         }
62     }
63     
64     @Override
65     public void markDirty() {
66         super.markDirty();
67         writeToNBT(this.itemStack.stackTagCompound);
68     }
69 }
先扔代码

相关文章:

  • 2022-12-23
  • 2021-12-04
  • 2022-12-23
  • 2021-11-17
  • 2021-08-18
  • 2022-12-23
  • 2021-11-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
  • 2021-07-10
  • 2022-12-23
相关资源
相似解决方案