零散工具类
两个很小的通用工具:一个补全 Gson 对象/数组,一个给 CodeChickenLib 的库存工具加一个"单趟插入"变体。
JsonUtil
包路径 makamys.mclib.json。Gson 的链式取值帮助类。
| 方法 | 签名 | 说明 |
|---|---|---|
| 取或建对象 | public static JsonObject getOrCreateObject(JsonObject obj, String memberName) |
已存在就返回,否则新建 JsonObject 并 add 进去 |
| 取或建数组 | public static JsonArray getOrCreateArray(JsonObject obj, String memberName) |
同上,类型为 JsonArray |
| 通用版 | public static JsonElement getOrCreateElement(JsonObject obj, String memberName, Supplier<JsonElement> memberConstructor) |
前两个方法的实现;已存在时直接返回原元素,不检查类型 |
第三个方法用 obj.has(memberName) 判断存在性,所以显式的 JSON null 也会被当成"已存在"并原样返回,不会被覆盖。
InventoryUtils2
包路径 makamys.mclib.ccl.inventory,为 CodeChickenLib 提供扩展。project.gradle 里 compile "codechicken:CodeChickenLib:1.7.10-1.1.3.140:dev",打包时 shade 配置要求排除 group: "codechicken",所以 CodeChickenLib 由宿主 mod 自己提供,MCLib 不携带。
| 方法 | 签名 |
|---|---|
| 单趟插入 | public static int insertItem(InventoryRange inv, ItemStack stack, boolean simulate, int pass) |
与 CCL 原版的差异
类里 import static codechicken.lib.inventory.InventoryUtils.* 复用原版的 fitStackInSlot 和 copyStack,只重写插入循环。源码注释:“和 InventoryUtils.insertItem 一样,但让你一次只跑一趟”。
原版 insertItem 一口气把空槽和有货槽都扫完;这里用 pass 参数把槽位分成两轮:
pass |
目标槽位 |
|---|---|
0 |
当前为空(base == null)的槽 |
非 0 |
当前有货(base != null)的槽 |
判定是 (pass == 0) == (base == null) 时 continue,即 pass 0 只填空槽、pass 非 0 只填已有堆叠。
行为细节
| 项 | 行为 |
|---|---|
| 入参 | 先 stack = stack.copy(),不改动调用方传入的 ItemStack |
| 有货槽 | stack.stackSize -= fit,非 simulate 时 base.stackSize += fit 并 setInventorySlotContents(slot, base) |
| 空槽 | 非 simulate 时 setInventorySlotContents(slot, copyStack(stack, fit)),然后 stack.stackSize -= fit |
| 提前退出 | stack.stackSize == 0 时立即 return 0 |
| 返回值 | 剩余没塞进去的数量(0 表示全部装下),与原版一致 |
simulate = true |
只计算不落盘 |
| 栈遍历顺序 | 按 inv.slots 数组顺序 |
相关条目
无。这两个类不与其他条目产生依赖关系。