From 3219738799e3f524f212803b90901b64a79af502 Mon Sep 17 00:00:00 2001 From: Djeeberjr Date: Thu, 28 Apr 2022 22:54:54 +0200 Subject: [PATCH] added TurtleExt --- src/lib/turtle/TurtleExt.hx | 98 +++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/lib/turtle/TurtleExt.hx diff --git a/src/lib/turtle/TurtleExt.hx b/src/lib/turtle/TurtleExt.hx new file mode 100644 index 0000000..6ee4535 --- /dev/null +++ b/src/lib/turtle/TurtleExt.hx @@ -0,0 +1,98 @@ +package lib.turtle; + +import kernel.turtle.Turtle; + +using tink.CoreApi; + +/** + Extends the Turtle kernel. +**/ +class TurtleExt { + public static function getFreeSlots(t: Turtle): Int { + var ret: Int = 0; + + for (i in 0...Turtle.MAX_SLOTS){ + if (t.getItemCount(i) == 0){ + ret++; + } + } + + return ret; + } + + public static function canPickup(t: Turtle,item: Item): Bool { + for (i in 0...Turtle.MAX_SLOTS){ + var slotItem = t.getItemDetail(i).orNull(); + if (slotItem != null && slotItem.name == item){ + if (t.getItemSpace(i)>0){ + return true; + } + } + } + + return false; + } + + public static function canPickupCount(t: Turtle,item: Item): Int { + var ret: Int = 0; + + for (i in 0...Turtle.MAX_SLOTS){ + var slotItem = Turtle.instance.getItemDetail(i).orNull(); + if (slotItem != null && slotItem.name == item){ + ret += Turtle.instance.getItemSpace(i); + } + } + + return ret; + } + + public static function getInventory(t: Turtle): Map { + var rtn: Map = new Map(); + + for (i in 0...Turtle.MAX_SLOTS){ + var slotItem = t.getItemDetail(i).orNull(); + if (slotItem != null){ + rtn.set(i, {item: slotItem.name, count: slotItem.count, free: t.getItemSpace(i)}); + } + } + + return rtn; + } + + /** + Optimize the turtle inventory. + TODO: does not work 100% yet. Can be optimized more i think. Not that it needs to be optimized. + **/ + public static function tidy(t: Turtle) { + var inv = getInventory(t); + // For each item in the inventory + for(k1 => v1 in inv){ + + if (v1.free == 0 || v1.count == 0){ + continue; + } + + for(k2 => v2 in inv){ + + if (k2 == k1){ + continue; + } + + if (v1.item == v2.item && v2.free > 0){ + // We can move an item in there + t.transfer(k1,k2,v2.free); + + v1.count -= v2.free; + if (v1.count <= 0){ + inv.remove(k1); + break; + } + } + + + } + } + + } + +}