Generalize slot iterator
This commit is contained in:
parent
96eb3c3491
commit
732039b321
@ -1,30 +0,0 @@
|
||||
package ru.dbotthepony.mc.otm.core
|
||||
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu
|
||||
import net.minecraft.world.item.ItemStack
|
||||
|
||||
class MenuIterator(private val menu: AbstractContainerMenu) : MutableIterator<ItemStack> {
|
||||
private var index = 0
|
||||
|
||||
override fun hasNext(): Boolean {
|
||||
return index < menu.slots.size
|
||||
}
|
||||
|
||||
override fun next(): ItemStack {
|
||||
if (index >= menu.slots.size) {
|
||||
throw IllegalStateException("Already finished iterating")
|
||||
}
|
||||
|
||||
return menu.slots[index++].item
|
||||
}
|
||||
|
||||
override fun remove() {
|
||||
if (index == 0) {
|
||||
throw IllegalStateException("Never called next()")
|
||||
}
|
||||
|
||||
menu.slots[index - 1].set(ItemStack.EMPTY)
|
||||
}
|
||||
}
|
||||
|
||||
fun AbstractContainerMenu.itemStackIterator() : MutableIterator<ItemStack> = MenuIterator(this)
|
26
src/main/kotlin/ru/dbotthepony/mc/otm/core/SlotIterator.kt
Normal file
26
src/main/kotlin/ru/dbotthepony/mc/otm/core/SlotIterator.kt
Normal file
@ -0,0 +1,26 @@
|
||||
package ru.dbotthepony.mc.otm.core
|
||||
|
||||
import net.minecraft.world.inventory.AbstractContainerMenu
|
||||
import net.minecraft.world.inventory.Slot
|
||||
import net.minecraft.world.item.ItemStack
|
||||
|
||||
private class SlotIterator(private val parent: Iterator<Slot>) : MutableIterator<ItemStack> {
|
||||
private var last: Slot? = null
|
||||
|
||||
override fun hasNext(): Boolean {
|
||||
return parent.hasNext()
|
||||
}
|
||||
|
||||
override fun next(): ItemStack {
|
||||
return parent.next().also { last = it }.item
|
||||
}
|
||||
|
||||
override fun remove() {
|
||||
val last = last ?: throw IllegalStateException("Never called next()")
|
||||
last.set(ItemStack.EMPTY)
|
||||
}
|
||||
}
|
||||
|
||||
fun AbstractContainerMenu.itemStackIterator() : MutableIterator<ItemStack> = SlotIterator(slots.iterator())
|
||||
fun List<Slot>.itemStackIterator() : MutableIterator<ItemStack> = SlotIterator(iterator())
|
||||
fun Iterator<Slot>.asItemStackIterator() : MutableIterator<ItemStack> = SlotIterator(this)
|
Loading…
Reference in New Issue
Block a user