Compare commits

...

2 Commits

Author SHA1 Message Date
3fce8d515a added InvManager.hx 2024-01-26 21:24:43 +01:00
fe88e065ab minor turtle improvements 2024-01-26 21:23:56 +01:00
3 changed files with 94 additions and 1 deletions

View File

@@ -257,7 +257,7 @@ class Turtle {
});
}
public static function getItemDetail(?detailed:Bool = false, ?slot:TurtleSlot):Option<ItemInspect> {
public static function getItemDetail(slot:TurtleSlot, ?detailed:Bool = false):Option<ItemInspect> {
var r = cc.Turtle.getItemDetail(slot + 1); // FIXME: can take detailed as flag. Has to be fixed upstream
if (r == null) {

View File

@@ -23,4 +23,7 @@ typedef ItemInspect = {
public var count:Int;
}
/**
The slot nummber for turtle inventory. 0 based.
**/
typedef TurtleSlot = Int;

View 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);
}
}