opus/sys/etc/scripts/follow

114 lines
2.3 KiB
Plaintext
Raw Normal View History

2016-12-11 19:24:52 +00:00
local function follow(id)
requireInjector(getfenv(1))
2017-07-28 23:01:59 +00:00
local Event = require('event')
local Point = require('point')
local Socket = require('socket')
2016-12-11 19:24:52 +00:00
turtle.status = 'follow ' .. id
2017-05-24 23:48:48 +00:00
if not turtle.enableGPS() then
2016-12-11 19:24:52 +00:00
error('turtle: No GPS found')
end
local socket = Socket.connect(id, 161)
if not socket then
error('turtle: Unable to connect to ' .. id)
return
end
local lastPoint
local following = false
2017-07-28 23:01:59 +00:00
Event.on('turtle_follow', function(_, pt)
2016-12-11 19:24:52 +00:00
2017-07-28 23:01:59 +00:00
local pts = {
{ x = pt.x + 2, z = pt.z, y = pt.y },
{ x = pt.x - 2, z = pt.z, y = pt.y },
{ x = pt.x, z = pt.z + 2, y = pt.y },
{ x = pt.x, z = pt.z - 2, y = pt.y },
}
local cpt = Point.closest(turtle.point, pts)
local blocks = { }
local function addBlocks(tpt)
table.insert(blocks, tpt)
local apts = Point.adjacentPoints(tpt)
for _,apt in pairs(apts) do
table.insert(blocks, apt)
2016-12-11 19:24:52 +00:00
end
2017-07-28 23:01:59 +00:00
end
2016-12-11 19:24:52 +00:00
2017-07-28 23:01:59 +00:00
-- don't run into player
addBlocks(pt)
addBlocks({ x = pt.x, z = pt.z, y = pt.y + 1 })
2016-12-11 19:24:52 +00:00
2017-07-28 23:01:59 +00:00
if turtle.pathfind(cpt, blocks) then
turtle.headTowards(pt)
end
following = false
end)
Event.onInterval(.5, function()
local function getRemotePoint()
if not turtle.abort then
if socket:write({ type = 'gps' }) then
return socket:read(3)
2016-12-11 19:24:52 +00:00
end
end
2017-07-28 23:01:59 +00:00
end
-- sometimes gps will fail if moving
local pt, d
2016-12-11 19:24:52 +00:00
2017-07-28 23:01:59 +00:00
for i = 1, 3 do
pt, d = getRemotePoint()
if pt then
break
2016-12-11 19:24:52 +00:00
end
2017-07-28 23:01:59 +00:00
os.sleep(.5)
end
2016-12-11 19:24:52 +00:00
2017-07-28 23:01:59 +00:00
if not pt or turtle.abort then
error('Did not receive GPS location')
end
2016-12-11 19:24:52 +00:00
2017-07-28 23:01:59 +00:00
if not lastPoint or (lastPoint.x ~= pt.x or lastPoint.y ~= pt.y or lastPoint.z ~= pt.z) then
2016-12-11 19:24:52 +00:00
2017-07-28 23:01:59 +00:00
if following then
turtle.abort = true
while following do
os.sleep(.1)
2016-12-11 19:24:52 +00:00
end
2017-07-28 23:01:59 +00:00
turtle.abort = false
2016-12-11 19:24:52 +00:00
end
2017-07-28 23:01:59 +00:00
-- check if gps is inaccurate (player moving too fast)
if d < Point.pythagoreanDistance(turtle.point, pt) + 10 then
lastPoint = Point.copy(pt)
following = true
os.queueEvent('turtle_follow', pt)
end
2016-12-11 19:24:52 +00:00
end
end)
2017-07-28 23:01:59 +00:00
Event.on('turtle_abort', function()
Event.exitPullEvents()
end)
Event.pullEvents()
2016-12-11 19:24:52 +00:00
socket:close()
return true
end
local s, m = turtle.run(function() follow({COMPUTER_ID}) end)
if not s and m then
error(m)
end