【问题标题】:How to know if an item can be stacked on other items of the same type on an inventory如何知道一个物品是否可以堆叠在库存中相同类型的其他物品上
【发布时间】:2022-01-03 19:50:11
【问题描述】:

所以我有一个播放器和一个商店插件。

商店试图给玩家 16 羊毛。

如果玩家有 1 到 63 毛线(Ofc 有另一个可用的 inv 空间),我的方法应该返回 true。但是,如果玩家只有 63 个羊毛并且他的其他空间充满了其他材料,则方法应该返回 false。我这里的问题是当玩家在inv.getContents()中有1、1、1个羊毛物品堆叠时,我的方法不会正确计算。

这是我的代码:

public static boolean canStackItemToInventory(Player player, ItemStack item) {
    Material type = item.getType();
    int amount = item.getAmount();
    if (type.equals(Material.BOW)) return false;
    PlayerInventory inventory = player.getInventory();

    int itemsNumber = 0;
    for (ItemStack itemStack : inventory.getContents()) {
        if (itemStack.getType()!=type) continue;
        if (itemStack.getAmount()==itemStack.getMaxStackSize()) continue;
        itemsNumber+=itemStack.getAmount();
    }
    itemsNumber+=amount;
    return itemsNumber <= type.getMaxStackSize();
}

【问题讨论】:

    标签: java minecraft bukkit


    【解决方案1】:

    我编写了这个函数,它应该根据玩家是否可以持有amount 的材料type 来返回真或假。我没有测试过,但它应该可以工作

    public boolean hasFreeSpace(Material type, int amount, Player player) {
            PlayerInventory inv = player.getInventory();
            //check if the player has any free slots
            if(inv.firstEmpty() == -1) {
                return false;
            }
            //we will decrement this until we need no more space
            int neededSpace = amount;
            //look through each itemstack
            for(ItemStack stack : inv.getContents()) {
                //check if that type of item is the same
                if(stack.getType() != type)
                    continue;
                //how many more items until the stack is full
                int untilStackIsFull = stack.getMaxStackSize() - stack.getAmount();
                //if the stack is full we will basically be subtracting zero, otherwise we subtract off how much it can hold
                neededSpace -= untilStackIsFull;
                //if we have all the space needed return true
                if(neededSpace <= 0)
                    return true;
            }
            return false;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2017-12-25
      相关资源
      最近更新 更多