Advertisement
Guest User

Untitled

a guest
Sep 16th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.24 KB | None | 0 0
  1. ```kotlin
  2. private fun Inventory.stackIsNotEmptyAndCanAddMore(toStack: ItemStack, stackToAdd: ItemStack): Boolean {
  3.     return !toStack.isEmpty &&
  4.             areItemsEqual(toStack, stackToAdd)
  5.             && toStack.isStackable
  6.             && toStack.count < toStack.maxCount
  7.             && toStack.count < this.invMaxStackAmount
  8. }
  9.  
  10. private fun areItemsEqual(stack1: ItemStack, stack2: ItemStack): Boolean {
  11.     return stack1.item === stack2.item && ItemStack.areTagsEqual(stack1, stack2)
  12. }
  13.  
  14. private fun Inventory.availableSlots(direction: Direction): Iterable<Int> {
  15.     return if (this is SidedInventory) getInvAvailableSlots(direction).toList() else (0 until invSize)
  16. }
  17.  
  18. private fun Inventory.canInsert(slot: Int, stack: ItemStack, direction: Direction): Boolean {
  19.     return if (this is SidedInventory) canInsertInvStack(slot, stack, direction) else isValidInvStack(slot, stack)
  20. }
  21.  
  22. private fun Inventory.distributeToAvailableSlots(stack: ItemStack, acceptEmptySlots: Boolean, direction: Direction): ItemStack {
  23.     val maxStackSize = invMaxStackAmount
  24.     var stackCountLeftToDistribute = stack.count
  25.     for (slot in availableSlots(direction)) {
  26.         if (!canInsert(slot, stack, direction)) continue
  27.  
  28.         val stackInSlot = getInvStack(slot)
  29.         if ((acceptEmptySlots && stackInSlot.isEmpty) || stackIsNotEmptyAndCanAddMore(stackInSlot, stack)) {
  30.             val amountThatCanFitInSlot = maxStackSize - stackInSlot.count
  31.             if (amountThatCanFitInSlot >= 0) {
  32.                 setInvStack(slot, ItemStack(stack.item,
  33.                         min(maxStackSize, stackInSlot.count + stackCountLeftToDistribute)
  34.                 ))
  35.                 stackCountLeftToDistribute -= amountThatCanFitInSlot
  36.             }
  37.         }
  38.  
  39.         if (stackCountLeftToDistribute <= 0) return ItemStack.EMPTY
  40.  
  41.     }
  42.  
  43.     return stack.copy(count = stackCountLeftToDistribute)
  44. }
  45.  
  46. /**
  47.  * Returns the remaining stack
  48.  */
  49. fun Inventory.insert(stack: ItemStack, direction: Direction = Direction.UP): ItemStack {
  50.     val remainingAfterNonEmptySlots = distributeToAvailableSlots(stack, acceptEmptySlots = false,direction = direction)
  51.     return distributeToAvailableSlots(remainingAfterNonEmptySlots, acceptEmptySlots = true,direction = direction)
  52. }
  53. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement