diff --git a/src/lib/turtle/InvManager.hx b/src/lib/turtle/InvManager.hx new file mode 100644 index 0000000..0c50d0a --- /dev/null +++ b/src/lib/turtle/InvManager.hx @@ -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; + +/** + 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 { + var invState = getInvState(); + var rtn:Map = 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 { + 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 { + 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 { + Turtle.selectSlot(slot); // TODO: handle error + return Turtle.place(dir); + } +}