refactored InvManager and State
This commit is contained in:
99
src/lib/turtle/InvState.hx
Normal file
99
src/lib/turtle/InvState.hx
Normal file
@@ -0,0 +1,99 @@
|
||||
package lib.turtle;
|
||||
|
||||
import kernel.turtle.Turtle;
|
||||
import kernel.turtle.TurtleSlot;
|
||||
|
||||
@:forward(get, set, iterator, keyValueIterator)
|
||||
abstract InvState(Map<TurtleSlot, {count:Int, name:Item, max:Int}>) {
|
||||
public function new() {
|
||||
this = new Map();
|
||||
for (i in 0...Turtle.MAX_SLOTS) {
|
||||
var detail = Turtle.getItemDetail(i);
|
||||
var spaceLeft = Turtle.getItemSpace(i);
|
||||
|
||||
switch detail {
|
||||
case Some(v):
|
||||
this.set(i, {
|
||||
count: v.count,
|
||||
name: v.name,
|
||||
max: spaceLeft + v.count
|
||||
});
|
||||
case None:
|
||||
this.remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
Count items.
|
||||
**/
|
||||
public function getItemCountInfo():Map<Item, Int> {
|
||||
var rtn:Map<Item, Int> = new Map();
|
||||
|
||||
for (slot in this) {
|
||||
if (!rtn.exists(slot.name)) {
|
||||
rtn.set(slot.name, slot.count);
|
||||
continue;
|
||||
}
|
||||
|
||||
var count = rtn.get(slot.name);
|
||||
rtn.set(slot.name, count + slot.count);
|
||||
}
|
||||
|
||||
return rtn;
|
||||
}
|
||||
|
||||
/**
|
||||
Return the slot with with the minimal count for an item.
|
||||
**/
|
||||
public function getSlotWithMinCountForItem(item:Item):Null<TurtleSlot> {
|
||||
var min:Int = 99; // TODO: is there something like MAX_INT ???
|
||||
var minSlot:TurtleSlot = -1;
|
||||
|
||||
for (k => slot in this) {
|
||||
if (slot.name != item) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (slot.count < min) {
|
||||
min = slot.count;
|
||||
minSlot = k;
|
||||
}
|
||||
};
|
||||
|
||||
return minSlot == -1 ? null : minSlot;
|
||||
}
|
||||
|
||||
/**
|
||||
Get all slots for an Item.
|
||||
**/
|
||||
public function getSlotsForItems():Map<Item, Array<TurtleSlot>> {
|
||||
var rtn:Map<Item, Array<TurtleSlot>> = new Map();
|
||||
|
||||
for (k => slot in this) {
|
||||
if (!rtn.exists(slot.name)) {
|
||||
rtn.set(slot.name, [k]);
|
||||
continue;
|
||||
}
|
||||
|
||||
var value = rtn.get(slot.name);
|
||||
value.push(k);
|
||||
rtn.set(slot.name, value);
|
||||
}
|
||||
|
||||
return rtn;
|
||||
}
|
||||
|
||||
/**
|
||||
Returns the first slot that contains this item.
|
||||
**/
|
||||
public function findItemSlot(item:Item):Null<TurtleSlot> {
|
||||
for (k => slot in this) {
|
||||
if (slot.name == item) {
|
||||
return k;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user