added InvManager.hx
This commit is contained in:
parent
fe88e065ab
commit
3fce8d515a
90
src/lib/turtle/InvManager.hx
Normal file
90
src/lib/turtle/InvManager.hx
Normal file
@ -0,0 +1,90 @@
|
||||
package lib.turtle;
|
||||
|
||||
import kernel.KernelEvents;
|
||||
import tink.CoreApi.Outcome;
|
||||
import kernel.log.Log;
|
||||
import kernel.turtle.Types.TurtleSlot;
|
||||
import kernel.turtle.Types.InteractDirections;
|
||||
import kernel.turtle.Turtle;
|
||||
|
||||
using Lambda;
|
||||
using tink.CoreApi;
|
||||
|
||||
typedef InvState = Map<TurtleSlot, {count:Int, name:Item, max:Int}>;
|
||||
|
||||
/**
|
||||
A wrapper for the native turtle inventory functions. Adds usefullt helper functions.
|
||||
**/
|
||||
class InvManager {
|
||||
public function new() {}
|
||||
|
||||
private static function getInvState() {
|
||||
var invState:InvState = new Map();
|
||||
for (i in 0...Turtle.MAX_SLOTS - 1) {
|
||||
var detail = Turtle.getItemDetail(i);
|
||||
var spaceLeft = Turtle.getItemSpace(i);
|
||||
|
||||
switch detail {
|
||||
case Some(v):
|
||||
invState.set(i, {
|
||||
count: v.count,
|
||||
name: v.name,
|
||||
max: spaceLeft + v.count
|
||||
});
|
||||
case None:
|
||||
invState.remove(i);
|
||||
}
|
||||
}
|
||||
return invState;
|
||||
}
|
||||
|
||||
public static function getItemCountInfo():Map<Item, Int> {
|
||||
var invState = getInvState();
|
||||
var rtn:Map<Item, Int> = new Map();
|
||||
|
||||
for (slot in invState) {
|
||||
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;
|
||||
}
|
||||
|
||||
private static function getSlotWithMinCountForItem(item:Item, invState:InvState):Null<TurtleSlot> {
|
||||
var min:Int = 99; // TODO: is there something like MAX_INT ???
|
||||
var minSlot:TurtleSlot = -1;
|
||||
|
||||
for (k => slot in invState) {
|
||||
if (slot.name != item) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (slot.count < min) {
|
||||
min = slot.count;
|
||||
minSlot = k;
|
||||
}
|
||||
};
|
||||
|
||||
return minSlot == -1 ? null : minSlot;
|
||||
}
|
||||
|
||||
public static function place(item:Item, dir:InteractDirections):Outcome<Noise, String> {
|
||||
var invState = getInvState();
|
||||
var slot = getSlotWithMinCountForItem(item, invState);
|
||||
if (slot == null) {
|
||||
return Failure("Item not in inventory");
|
||||
}
|
||||
|
||||
return placeSlot(slot, dir);
|
||||
}
|
||||
|
||||
private static function placeSlot(slot:TurtleSlot, dir:InteractDirections):Outcome<Noise, String> {
|
||||
Turtle.selectSlot(slot); // TODO: handle error
|
||||
return Turtle.place(dir);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user