diff --git a/kai/lib.lua b/kai/lib.lua new file mode 100644 index 0000000..7d8b45e --- /dev/null +++ b/kai/lib.lua @@ -0,0 +1,76 @@ +-- Do not lose state when reset (chunkloading etc) +state = (function () + local path = ".state" + local state_table = {} + + if fs.exists(path) then + local f = fs.open(path, "r") + state_table = textutils.unserialize(f.readAll()) + f.close() + end + + return setmetatable({}, { + __index = state_table, + + __newindex = function(self, k, v) + rawset(state_table, k, v) + local f = fs.open(path, "w") + f.write(textutils.serialize(state_table)) + f.close() + end, + }) +end)() + +--[[ + orientation: + 0 = South (+z) + 1 = West (-x) + 2 = North (-z) + 3 = East (+x) +]] + +function move(raw_move, position_update) + return function() + success, err = raw_move() + if not success then + return false, err + end + position_update() + end +end + +return { + state = state, + + fwd = move(turtle.forward, function() + if state.o == 1 or state.o == 3 then + state.x = state.x + ((state.o == 1) and -1 or 1) + else + state.z = state.z + ((state.o == 2) and -1 or 1) + end + end), + + back = move(turtle.back, function() + if state.o == 1 or state.o == 3 then + state.x = state.x + ((state.o == 1 and 1 or -1)) + else + state.z = state.z + ((state.o == 2) and 1 or -1) + end + end), + + up = move(turtle.up, function() + state.y = state.y + 1 + end), + + down = move(turtle.down, function() + state.y = state.y - 1 + end), + + left = move(turtle.turnLeft, function() + state.o = (state.o - 1) % 4 + end), + + right = move(turtle.turnRight, function() + state.o = (state.o + 1) % 4 + end), +} \ No newline at end of file