Skip to content

Instantly share code, notes, and snippets.

@L0laapk3
Created August 6, 2022 16:14
Show Gist options
  • Save L0laapk3/d8ae2547ccf80237099b57e26203a03c to your computer and use it in GitHub Desktop.
Save L0laapk3/d8ae2547ccf80237099b57e26203a03c to your computer and use it in GitHub Desktop.
computercraft turtle position tracker
local V = vector.new
local R = function(v, r)
local f = r > 1 and -1 or 1
if r % 2 == 1 then
return V(-v.z * f, v.y, v.x * f)
end
return V(v.x * f, v.y, v.z * f)
end
moveUpdates = {
forward = {1, 0, 0, 0},
back = {-1, 0, 0, 0},
turnLeft = {0, 0, 0, -1},
turnRight = {0, 0, 0, 1},
up = {0, 1, 0, 0},
down = {0, -1, 0, 0}
}
function savePos()
local h = fs.open("/.pos", "w")
h.write(textutils.serialize(turtle.pos))
h.close()
--print(unpack(turtle.pos))
end
function loadPos()
local h = fs.open("/.pos", "r")
if h ~= nil then
turtle.pos = textutils.unserialize(h.readAll())
h.close()
term.setTextColor(0x100)
term.write("current position is: ")
term.setTextColor(0x2000)
print(turtle.pos[1], turtle.pos[2], turtle.pos[3], string.sub("ESWN", turtle.pos[4] + 1, turtle.pos[4] + 1))
term.setTextColor(0x100)
print("if incorrect, 'rm /.pos' and reboot")
term.setTextColor(1)
else
local p = {}
term.setTextColor(0x2000)
print("Please enter turtle coordinates")
term.setTextColor(1)
term.write("x: ")
p[1] = tonumber(read())
assert(p[1] ~= nil)
term.write("y: ")
p[2] = tonumber(read())
assert(p[2] ~= nil)
term.write("z: ")
p[3] = tonumber(read())
assert(p[3] ~= nil)
term.write("orientation (N/E/S/W): ")
local ori = string.upper(read())
if ori == "E" then
p[4] = 0
elseif ori == "S" then
p[4] = 1
elseif ori == "W" then
p[4] = 2
elseif ori == "N" then
p[4] = 3
end
assert(p[4] ~= nil)
turtle.pos = p
savePos()
end
end
term.clear()
term.setCursorPos(1, 1)
loadPos()
for k, move in pairs(moveUpdates) do
local fn = turtle[k]
turtle[k] = function()
local oldPos = turtle.pos
local posV = V(unpack(oldPos)) + R(V(unpack(move)), oldPos[4])
turtle.pos = { posV.x, posV.y, posV.z, (oldPos[4] + 4 + move[4]) % 4 }
savePos()
local r = fn()
if not r then
turtle.pos = oldPos
savePos()
end
return r
end
end
@L0laapk3
Copy link
Author

L0laapk3 commented Aug 6, 2022

In the process I also made a simple move from keystroke script: https://pastebin.com/C9czv3Zr

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment