Advertisement
KDKiller

CC Turtle Lib

Jan 17th, 2021 (edited)
772
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.10 KB | None | 0 0
  1. -- Let dir 0-3 be {N, E, S, W}
  2. -- east is positive x, south is positive z
  3.  
  4. directions = {'north','east','south','west'}
  5.  
  6. default = {x=0,y=0,z=0,direction=0}
  7.  
  8. function save(table,filename)
  9.     local file = fs.open(filename,"w")
  10.     file.write(textutils.serialize(table))
  11.     file.close()
  12. end
  13.  
  14. function load(filename)
  15.     local file = fs.open(filename,"r")
  16.     local data = textutils.unserialize(file.readAll())
  17.     file.close()
  18.     return data
  19. end
  20.  
  21. function dir(dir)
  22.     for i, v in pairs(directions) do
  23.         if string.lower(dir) == v then
  24.             return i
  25.         end
  26.     end
  27.     return false
  28. end
  29.  
  30. function forward(dist)
  31.     if not turtle then return end
  32.     pos = getPos('locale')
  33.     if turtle.forward() then
  34.         dx = math.floor(math.cos((pos['direction']-1)*math.pi/2))
  35.         dz = -math.floor(math.cos(pos['direction']*math.pi/2))
  36.         pos['x'] = pos['x'] + dx
  37.         pos['z'] = pos['z'] + dz
  38.         save(pos,'locale')
  39.         return true
  40.     end
  41.     return false
  42. end
  43. fwd = forward
  44.  
  45. function right()
  46.     if not turtle then return end
  47.     pos = getPos('locale')
  48.     if turtle.turnRight() then
  49.         pos['direction'] = (pos['direction'] + 1)%4
  50.         save(pos,'locale')
  51.         return true
  52.     end
  53.     return false
  54. end
  55.  
  56. function left()
  57.     if not turtle then return end
  58.     pos = getPos('locale')
  59.     if turtle.turnLeft() then
  60.         pos['direction'] = (pos['direction'] - 1)%4
  61.         save(pos,'locale')
  62.         return true
  63.     end
  64.     return false
  65. end
  66.  
  67. function up()
  68.     if not turtle then return end
  69.     pos = getPos('locale')
  70.     if turtle.up() then
  71.         pos['y'] = pos['y'] + 1
  72.         save(pos,'locale')
  73.         return true
  74.     end
  75.     return false
  76. end
  77.  
  78. function down()
  79.     if not turtle then return end
  80.     pos = getPos('locale')
  81.     if turtle.down() then
  82.         pos['y'] = pos['y'] - 1
  83.         save(pos,'locale')
  84.         return true
  85.     end
  86.     return false
  87. end
  88.  
  89. function getPos()
  90.     if not turtle then return end
  91.     if not fs.exists('locale') then
  92.         save(default, 'locale')
  93.     end
  94.     return load('locale')
  95. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement