58 lines
1.2 KiB
Kotlin
58 lines
1.2 KiB
Kotlin
package ru.dbotthepony.kstarbound.player
|
|
|
|
import com.google.common.collect.ImmutableList
|
|
import ru.dbotthepony.kstarbound.defs.player.InventoryConfig
|
|
import ru.dbotthepony.kstarbound.util.ItemStack
|
|
import java.util.function.Predicate
|
|
|
|
class AvatarBag(val avatar: Avatar, val config: InventoryConfig.Bag, val filter: Predicate<ItemStack>) {
|
|
private val slots = ImmutableList.builder<Slot>().let {
|
|
for (i in 0 until config.size) {
|
|
it.add(Slot())
|
|
}
|
|
|
|
it.build()
|
|
}
|
|
|
|
private class Slot {
|
|
var item: ItemStack? = null
|
|
|
|
fun mergeFrom(value: ItemStack, simulate: Boolean) {
|
|
if (item == null) {
|
|
if (!simulate) {
|
|
item = value.copy().also { it.count = value.count.coerceAtMost(value.item!!.value.maxStack) }
|
|
}
|
|
|
|
value.count -= value.item!!.value.maxStack
|
|
} else {
|
|
item!!.mergeFrom(value, simulate)
|
|
}
|
|
}
|
|
}
|
|
|
|
operator fun set(index: Int, value: ItemStack?) {
|
|
slots[index].item = value
|
|
}
|
|
|
|
operator fun get(index: Int): ItemStack? {
|
|
return slots[index].item
|
|
}
|
|
|
|
fun put(item: ItemStack, simulate: Boolean): ItemStack {
|
|
if (!filter.test(item))
|
|
return item
|
|
|
|
val copy = item.copy()
|
|
|
|
for (slot in slots.indices) {
|
|
slots[slot].mergeFrom(copy, simulate)
|
|
|
|
if (copy.isEmpty) {
|
|
return copy
|
|
}
|
|
}
|
|
|
|
return copy
|
|
}
|
|
}
|