t8rt0t

patternAPI.lua

Mar 20th, 2024 (edited)
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 42.88 KB | None | 0 0
  1. --Turt api to replace the default turtle api for cc turtles (turt api logs stats, and has some edge cases improved)
  2. if not turt then os.loadAPI("apis/turt.lua") end
  3.  
  4. --Documentation API to let people get method summaries easier
  5. if not docs then os.loadAPI("apis/docs.lua") end
  6. --Type registry
  7. local types = {
  8.     ["Pattern"]={colors.orange,"A 2D array of characters that represents a pattern to be mined. Lowercase characters are yet to be explored, uppercase characters are already explored, and non-alphanumeric characters are invalid"},
  9.     ["NodeMap"]={colors.orange,"A 2D array of Nodes that are used for pathfinding"},
  10.     ["Node"]={colors.brown,"Used for pathfinding, this stores A* function values as well as other data"},
  11.     ["Map"]={colors.orange,"A map of 0s and 1s used for approximating Hamiltonian paths"},
  12.     ["TurtleData"]={colors.brown,"Stores turtle data such as position, horizontal rotation, and pathfinding rotation"}
  13. }
  14. for k,v in pairs(types) do
  15.     docs.registerType(k,v[1],v[2])
  16. end
  17.  
  18. --Seperates a string into a table by a seperator character
  19. --@Arg string input: The input string to be split
  20. --@OptionalArg string sep: The character, or character class to seperate the string by
  21. --@Returns table splitString: A list of strings that got seperated
  22. local function split(input,sep)
  23.     sep = sep or "%s"
  24.     local t = {}
  25.     for str in string.gmatch(input,"([^"..sep.."]+)") do
  26.         table.insert(t,str)
  27.     end
  28.     return t
  29. end
  30. --Recursively counts the number of specific elements inside a table
  31. --@Arg table array: The table to search through
  32. --@OptionalArg function filter: A function that returns true if the element should be counted, or false otherwise
  33. --@Returns number count: The number of elements that were found
  34. local function countElements(array,filter)
  35.     local count = 0
  36.     for k,v in pairs(array) do
  37.         if type(v) ~= "table" then
  38.             if type(filter) ~= "function" or filter(v) then
  39.                 count = count+1
  40.             end
  41.         else
  42.             count = count+countElements(v,filter) --If element is a table, then the function will recursively count the elements inside the table
  43.         end
  44.     end
  45.     return count
  46. end
  47. --Copies a table
  48. --@Arg table tab: The table to be copied
  49. --@Returns table t: A copy of the table inputted
  50. local function copyTable(tab)
  51.     local t = {}
  52.     for k,v in pairs(tab) do
  53.         if type(v) == "table" then
  54.             t[k] = copyTable(v)
  55.         else
  56.             t[k] = v
  57.         end
  58.     end
  59.     return t
  60. end
  61. --Reverses tables, useful for moving along a table
  62. --@Arg table tab: The table in forward order. Should have integer keys
  63. --@Returns table t: The same table, in reverse order.
  64. local function reverseTable(tab)
  65.     local t = {}
  66.     while #tab > 0 do
  67.         table.insert(t,table.remove(tab))
  68.     end
  69.     --for k,v in ipairs(tab) do
  70.         --t[#tab-k+1] = v
  71.     --end
  72.     return t
  73. end
  74. --Returns a list of keys in a table
  75. --@Arg table tab: The table to retrieve the keys from
  76. --@Returns table t: A list of the keys of the original table
  77. local function getKeys(tab)
  78.     local t = {}
  79.     for k,v in pairs(tab) do
  80.         table.insert(t,k)
  81.     end
  82.     return t
  83. end
  84. --Takes a rotation and turns it into a vector
  85. --Rotation in this program is defined as 0 being "up", 1 being right, 2 being down, and 3 being left
  86. --@OptionalArg number rot: The rotation, from 0-3, to be turned into a vector
  87. --@Returns Vector2D v: A vector with magnitude 1 that represents the rotation
  88. function rotToXY(rot)
  89.     rot = rot or 0
  90.     rot = rot%4
  91.     return {math.floor(math.sin(math.pi*rot/2)+0.5),-math.floor(math.cos(math.pi*rot/2)+0.5)}
  92. end
  93. --Gets the first target found from a map
  94. --@Arg Map map: The map to search for a valid target
  95. --@OptionalArg function filter: The filter function to determine whether an element is a valid target or not
  96. --@Returns Vector2D v: The location of a possible target in {x,y}
  97. --@Returns boolean false: If no target was found
  98. local function getTarget(map,filter)
  99.     for k,v in pairs(map) do
  100.         for j,w in pairs(v) do
  101.             if type(filter) ~= "function" or filter(w) then return {j,k} end
  102.         end
  103.     end
  104.     return false
  105. end
  106. --Updates the turtle's position based on its current pathfinding rotation
  107. --@Arg TurtleData this: the turtle information to be updated
  108. --@OptionalArg number amount: How much the turtle should move
  109. local function updatePos(this,amount)
  110.     amount = amount or 1
  111.     local v = rotToXY(this.rot)
  112.     this.pos.x = this.pos.x+amount*v[1]
  113.     this.pos.y = this.pos.y+amount*v[2]
  114. end
  115. --Safer way of getting elements
  116. --@Arg table matrix: A 2D table to get the element from
  117. --@Arg number x: The first index of the matrix to search
  118. --@Arg number y: the second index of the matrix to search
  119. --@OptionalArg any default: What to return if the element does not exist or if it fails the filter
  120. --@OptionalArg function filterFunction: Filters the matrix element, possibly returning the default if it fails
  121. --@Returns any element: The matrix element found
  122. --@Returns any default: The default value if the element could not be found or if it failed the filter
  123. function getMatrixElement(matrix,x,y,default,filterFunction)
  124.     if type(matrix) ~= "table" or type(matrix[x]) ~= "table" or not matrix[x][y] then return default end
  125.     if type(filterFunction) == "function" then
  126.         return filterFunction(matrix[x][y],default,x,y)
  127.     else
  128.         return matrix[x][y]
  129.     end
  130. end
  131. --Safer way of setting elements
  132. --@Arg table matrix: The 2d table to be updated
  133. --@Arg number x: The first index of the matrix to edit
  134. --@Arg number y: The second index of the matrix to edit
  135. --@Arg any element: The new data value of the matrix at the position
  136. function setMatrixElement(matrix,x,y,element)
  137.     if type(matrix) ~= "table" then matrix = {} end
  138.     if type(matrix[x]) ~= "table" then matrix[x] = {} end
  139.     matrix[x][y] = element
  140. end
  141. --Does cheap digs without moving to them
  142. --@Arg Pattern pattern: The pattern to use to decide whether the turtle should mine a specific block
  143. --@Arg TurtleData this: Information about the turtle such as its position
  144. --@OptionalArg boolean skipDigging: Whether the function should not actually interact with the world, but only update the pattern
  145. --@Returns table digsDone: A list of rotations of the directions that the turtle mined
  146. local function doCheapDigsXY(pattern,this,skipDigging)
  147.     local dirs = {
  148.         rotToXY(this.horizRot),
  149.         rotToXY(0),
  150.         rotToXY(1)
  151.     }
  152.     digsDone = {}
  153.     for k,v in pairs(dirs) do
  154.         local char = getMatrixElement(pattern,this.pos.y+v[2],this.pos.x+v[1]," ",function(element,default) return type(element) == "string" and element or default end)
  155.         if string.match(char,"%l") then
  156.             if not skipDigging then
  157.                 local j = this.horizRot
  158.                 if k == 1 then
  159.                     turt.dig()
  160.                 elseif k == 2 then
  161.                     turt.digUp()
  162.                     j = 0
  163.                 elseif k == 3 then
  164.                     turt.digDown()
  165.                     j=1
  166.                 end
  167.             end
  168.             table.insert(digsDone,j)
  169.             setMatrixElement(pattern,this.pos.y+v[2],this.pos.x+v[1],string.upper(char))
  170.         end
  171.     end
  172.     return digsDone
  173. end
  174. --Does cheap digs without moving to them
  175. --@Arg Pattern pattern: The pattern to use to decide whether the turtle should mine a specific block
  176. --@Arg TurtleData this: Information about the turtle such as its position
  177. --@OptionalArg boolean skipDigging: Whether the function should not actually interact with the world, but only update the pattern
  178. --@Returns table digsDone: A list of rotations of the directions that the turtle mined
  179. local function doCheapDigs(pattern,this,skipDigging)
  180.     v = rotToXY(this.rot)
  181.     local char = getMatrixElement(pattern,this.pos.y+v[2],this.pos.x+v[1]," ",function(element,default) return type(element) == "string" and element or default end)
  182.     if string.match(char,"%l") then
  183.         if not skipDigging then
  184.             turt.dig()
  185.         end
  186.         setMatrixElement(pattern,this.pos.y+v[2],this.pos.x+v[1],string.upper(char))
  187.         return {this.rot}
  188.     end
  189. end
  190. --Patterns are 2d arrays of characters
  191. --Lowercase characters are valid paths, all others are either already visited or invalid
  192. --The maps used here are a matrix of 0 and 1s
  193. --@Arg Pattern pattern: The serialized pattern to generate the map from
  194. --@Returns Map map, Vector2D startPos: The map and the starting position for the turtle
  195. function generateMapFromPattern(pattern)
  196.     local height = 0
  197.     local width = 0
  198.     local startPos = {} --In horizontal coordinates, of course
  199.     for k,v in ipairs(pattern) do
  200.         local rowWidth = 0
  201.         for j,w in ipairs(v) do
  202.             if type(w) == "string" and string.match(w,"%l") then
  203.                 rowWidth = j
  204.                 height = k
  205.             end
  206.             if type(w) == "string" and string.match(w,"[aA]") then
  207.                 startPos = {j,k}
  208.             end
  209.         end
  210.         width = math.max(rowWidth,width)
  211.     end
  212.     local t = {}
  213.     for i=1,height do
  214.         local row = {}
  215.         for j=1,width do
  216.             if pattern[i] and type(pattern[i][j]) == "string" and string.match(pattern[i][j],"%l") then
  217.                 row[j] = 1
  218.             else
  219.                 row[j] = 0
  220.             end
  221.         end
  222.         t[i] = row
  223.     end
  224.     return t,startPos
  225. end
  226. --Counts the number of valid (1s) neighbors around a specific position
  227. --@Arg Map map: the map to be used to decide if a tile is valid
  228. --@Arg Vector2D pos: The x and y coordinates of the tile whose neighbors get searched
  229. --@Returns number count: How many neighbors were valid (1s)
  230. local function countValidNeighbors(map,pos)
  231.     local count = 0
  232.     for i=0,3 do
  233.         local v = rotToXY(i)
  234.         if getMatrixElement(map,pos[2]+v[2],pos[1]+v[1],0,function(element,default) return tonumber(element) or default end) > 0 then
  235.             count = count + 1
  236.         end
  237.     end
  238.     return count
  239. end
  240. --Gets the next map move
  241. --The function prioritizes the next node with the least number of valid neighbors (but still having at least one more neighbor to travel to)
  242. --As a tiebreaker, the function also prioritizes doing the least number of right turns (biased towards moving straight, and biased against going left)
  243. --@Arg Map map: The map of traversable and inaccessable tiles
  244. --@Arg Vector2D pos: The position around which to get the next move
  245. --@OptionalArg number lastMove: The rotation of the last move
  246. --@Returns number rot: The rotation to travel to, or -1 if there is no valid move
  247. local function getNextMapMove(map,pos,lastMove)
  248.     lastMove = tonumber(lastMove) or 0
  249.     setMatrixElement(map,pos[2],pos[1],0)
  250.     local moveMap = {} --Sorting moves by their costs
  251.     local lowestScore = 69
  252.     for i=0,3 do
  253.         local v = rotToXY(i)
  254.         if getMatrixElement(map,pos[2]+v[2],pos[1]+v[1],0,function(element,default) return tonumber(element) or default end) > 0 then
  255.             local countScore = countValidNeighbors(map,{pos[1]+v[1],pos[2]+v[2]})--Least number of neighbors (but more than 0) is preferable
  256.             if countScore <= 0 then countScore = 4 end
  257.             countScore = countScore*4 --Scaling countscore to make it more influential than rotation score
  258.             local rotationScore = (i-lastMove)%4 --Least number of right turns needed to take to do the move is preferable
  259.             moveMap[i] = countScore+rotationScore
  260.             lowestScore = math.min(lowestScore,countScore+rotationScore)
  261.         end
  262.     end
  263.     for i=0,3 do
  264.         if moveMap[i] then
  265.             if moveMap[i] <= lowestScore then return i end
  266.         end
  267.     end
  268.     return -1
  269. end
  270. --Idea stolen from stackexchange
  271. --Basically, prioritizing travelling to nodes with the least number of connecting nodes (but still with connecting nodes)
  272. --@Arg Map map: The map to generate the path from
  273. --@Arg Vector2D startPos: The starting position to generate the path from
  274. --@Returns table moves: A list of moves in order of the first move to take to the last move to take, in terms of rotations (0-3)
  275. local function getHamiltonianPath(map,startPos)
  276.     local moves = {}
  277.     local pos = startPos
  278.     local move = getNextMapMove(map,pos,0)
  279.     while move >= 0 do
  280.         table.insert(moves,move)
  281.         local v = rotToXY(move)
  282.         pos = {pos[1]+v[1],pos[2]+v[2]}
  283.         move = getNextMapMove(map,pos,move)
  284.     end
  285.     return moves
  286. end
  287. --Will move the turtle in the direction specified, but on the XY plane
  288. --Also updates the pattern so the tile under where the turtle is turns upper case (which means already explored)
  289. --@Arg number dir: The direction to move the turtle in
  290. --@Arg TurtleData this: Information about the turtle
  291. --@Arg Pattern pattern: The pattern to be updated as the turtle moves
  292. local function rawMoveXY(dir,this,pattern)
  293.     dir = dir%4
  294.     --0 means straight up, in the xy plane
  295.     if dir == 0 then
  296.         turt.digUp()
  297.         turt.up()
  298.         this.rot = 0
  299.         updatePos(this)
  300.     --2 means straight down
  301.     elseif dir == 2 then
  302.         turt.digDown()
  303.         turt.down()
  304.         this.rot = 2
  305.         updatePos(this)
  306.     --TODO: This will break stuff if the last direction mined was up or down, need to fix
  307.     --Fixed??
  308.     --elseif this.rot == dir then
  309.         --turt.dig()
  310.         --turt.forward()
  311.         --updatePos(this)
  312.     --else
  313.         --turt.turnLeft(2)
  314.         --turt.dig()
  315.         --turt.forward()
  316.         --this.rot = dir
  317.         --updatePos(this)
  318.     --end
  319.     else
  320.         while this.horizRot ~= dir do
  321.             turt.turnRight()
  322.             this.horizRot = (this.horizRot+1)%4
  323.         end
  324.         this.rot = this.horizRot
  325.         turt.dig()
  326.         turt.forward()
  327.         updatePos(this)
  328.     end
  329.     pattern[this.pos.y] = pattern[this.pos.y] or {}
  330.     pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " " --So it doesnt lose its shit
  331.     pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
  332.     --if map then setMatrixElement(map,this.pos.y,this.pos.x,0) end
  333. end
  334. --Same as moveXY, but on the XZ plane instead, meaning that dir=0 is 'forward' in the original reference frame
  335. --@Arg number dir: The direction to move the turtle in
  336. --@Arg TurtleData this: Information about the turtle
  337. --@Arg Pattern pattern: The pattern to be updated as the turtle moves
  338. local function rawMove(dir,this,pattern)
  339.     dir = dir%4
  340.     while this.rot ~= dir do
  341.         turt.turnRight()
  342.         this.rot = (this.rot+1)%4
  343.     end
  344.     turt.dig()
  345.     turt.forward()
  346.     updatePos(this)
  347.     pattern[this.pos.y] = pattern[this.pos.y] or {}
  348.     pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " " --See above
  349.     pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
  350.     this.horizRot = this.rot
  351.     --if map then setMatrixElement(map,this.pos.y,this.pos.x,0) end
  352. end
  353. --"Pretends" to do a move, meaning it will only update a pattern, good for testing
  354. --@Arg number dir: The direction to move the turtle in
  355. --@Arg TurtleData this: Information about the turtle
  356. --@Arg Pattern pattern: The pattern to be updated as the turtle moves
  357. local function simulateRawMove(dir,this,pattern)
  358.     dir = dir%4
  359.     while this.rot ~= dir do
  360.         --turt.turnRight()
  361.         this.rot = (this.rot+1)%4
  362.     end
  363.     --turt.dig()
  364.     --turt.forward()
  365.     updatePos(this)
  366.     pattern[this.pos.y] = pattern[this.pos.y] or {}
  367.     pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " " --See above
  368.     pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
  369.     --if map then setMatrixElement(map,this.pos.y,this.pos.x,0) end
  370. end
  371. --Does a move in XY, with the addition of doing "cheap digs" that require no movement or rotation
  372. --@Arg number dir: The direction to move the turtle in
  373. --@Arg TurtleData this: Information about the turtle
  374. --@Arg Pattern pattern: The pattern to be updated as the turtle moves
  375. local function doMoveXY(dir,this,pattern)
  376.     doCheapDigsXY(pattern,this,false)
  377.     rawMoveXY(dir,this,pattern)
  378.     doCheapDigsXY(pattern,this,false)
  379. end
  380. --Does a move, with the addition of doing "cheap digs" that require no movement or rotation
  381. --@Arg number dir: The direction to move the turtle in
  382. --@Arg TurtleData this: Information about the turtle
  383. --@Arg Pattern pattern: The pattern to be updated as the turtle moves
  384. local function doMove(dir,this,pattern)
  385.     doCheapDigs(pattern,this,false)
  386.     rawMove(dir,this,pattern)
  387.     doCheapDigs(pattern,this,false)
  388. end
  389. --Simulates a move, with the addition of simulating "cheap digs" that require no movement or rotation
  390. --@Arg number dir: The direction to "move" the turtle in
  391. --@Arg TurtleData this: Information about the turtle
  392. --@Arg Pattern pattern: The pattern to be updated as the turtle "moves"
  393. --@Arg string mode: "xy" to simulate in xy, "xz" to simulate in xz
  394. local function simulateMove(dir,this,pattern,mode)
  395.     if mode == "xy" then
  396.         doCheapDigsXY(pattern,this,true)
  397.     else
  398.         doCheapDigs(pattern,this,true)
  399.     end
  400.     simulateRawMove(dir,this,pattern)
  401.     if mode == "xy" then
  402.         doCheapDigsXY(pattern,this,true)
  403.     else
  404.         doCheapDigs(pattern,this,true)
  405.     end
  406. end
  407. --Node layout = {x=,y=,f=,g=,h=,p=[x,y],r=r}
  408. --Gets the new node next to the orignal node in the direction specified
  409. --@Arg NodeMap nodeMap: The map of nodes to be filled out
  410. --@Arg Node node: The parent node to be generated
  411. --@Arg Vector2D endingPoint: The coordinates of the ending position, for generating A* heuistics
  412. --@Arg number direction: The direction to generate the new node in, starting from the parent node
  413. --@Returns boolean false: If the tile to generate the new node in is unpassable or if the node was already generated
  414. --@Returns Node newNode: The new node that got created
  415. local function getNode(nodeMap,node,endingPoint,direction)
  416.     --Turning direction into a vector that can be added
  417.     local v = rotToXY(direction)
  418.     --X and y coordinates of the new node
  419.     local x,y = node.x+v[1],node.y+v[2]
  420.     --Returning nil if the nodeMap already has a node at the tile, or if the tile is not valid to be traversed
  421.     if not nodeMap[y] then return end
  422.     if type(nodeMap[y][x]) ~= "string" or not string.match(nodeMap[y][x],"%w") then return false end
  423.     --Calculating A* Heuristic with manhattan distance
  424.     local h = math.abs(x - endingPoint[1]) + math.abs(y - endingPoint[2])
  425.     --Calculating A* Cost, which is just the number of moves it takes to get to this node
  426.     local g = node.g+1
  427.     --Putting in parent node location
  428.     local p = {node.x,node.y}
  429.     --Putting in the rotation to be used by turtles
  430.     local r = (direction)%4
  431.     local newNode = {x=x,y=y,f=g+h,g=g,h=h,p=p,r=r}
  432.     --nodeMap[y][x] = newNode //Got rid of this because it's moved to the getNeighborNodes function
  433.     return newNode
  434. end
  435. --Nodes to Check is a table of the nodes that still haven't been explored, sorted by their f value (As lower f value nodes are the ones that get prioritized)
  436. --NodeMap starts off as just a copy of the Pattern map, but as nodes get filled in, the pattern gets replaced by nodes
  437. --Nodes to check structure: {f value: [node1,node2,...]}
  438. --@Arg NodeMap nodeMap: The nodeMap to be updated
  439. --@Arg Node node: The parent node for the neighbors
  440. --@Arg Vector2D endingPoint: The ending point that is being navigated towards
  441. --@Arg table nodesToCheck: A list of Nodes that still have not been checked, sorted by their function value
  442. local function getNeighborNodes(nodeMap,node,endingPoint,nodesToCheck)
  443.     if node.h <= 0 then return {},true end --If the node you're checking is at the end position, don't need to check neighbor nodes
  444.     local nodes = {}
  445.     local hasFoundEnd = false --Has found end flag to let the nodeMap functions know when to stop
  446.     for i=0,3 do --For each direction, gets the nodes (or nil if invalid condition as stated in previous function)
  447.         local newNode = getNode(nodeMap,node,endingPoint,i) --Gets the node in the direction
  448.         if newNode then
  449.             if not nodeMap[newNode.y] then nodeMap[newNode.y] = {} end --Shouldnt need but just in case
  450.             nodeMap[newNode.y][newNode.x] = newNode --Adds node to the nodeMap
  451.             if newNode.h <= 0 then hasFoundEnd = true end --If h value is 0, then that node is the ending node
  452.             table.insert(nodes,newNode) --the nodes table doesnt really get used anyway, but keeping it because why not
  453.             if type(nodesToCheck[newNode.f]) ~= "table" then nodesToCheck[newNode.f] = {} end --If there isnt already a table for that function value, creates one so that the node can be inserted into it
  454.             table.insert(nodesToCheck[newNode.f],newNode)
  455.         end
  456.     end
  457.     return nodes,hasFoundEnd,nodesToCheck
  458. end
  459. --Gets nodes to check
  460. --Might break if f value is ever 0 (you pathfind starting at the ending pos)
  461. --@Arg table nodesToCheck: A list of nodes to check, sorted by function value.
  462. --@Returns Node node, table nodesToCheck: If successful, returns the node with the lowest function value
  463. --@Returns boolean false, table nodesToCheck: If not successful, returns false
  464. local function getNodeToCheck(nodesToCheck)
  465.     for k,v in pairs(nodesToCheck) do
  466.         if type(v) == "table" and #v > 0 then return table.remove(v),nodesToCheck end
  467.     end
  468.     return false, nodesToCheck
  469. end
  470. --Recursively generates the node map from the pattern map until an end is found
  471. --@Arg NodeMap nodeMap: The nodeMap to be filled out
  472. --@Arg Node node: The initial node to build off of
  473. --@Arg Vector2D endingPoint: The position to navigate towards
  474. --@Arg table nodesToCheck: A list of nodes to check, sorted by function value
  475. --@OptionalArg boolean printDebug: Deprecated, but prints the node to be checked
  476. local function buildNodeMap(nodeMap,node,endingPoint,nodesToCheck,printDebug)
  477.     if not nodeMap[endingPoint[2]] then return false end --Makes it avoid shitting itself
  478.     --If the element at the end position is a table (node), then the function is complete
  479.     if type(nodeMap[endingPoint[2]][endingPoint[1]]) == "table" then return true end
  480.     --If there are no more nodes to check, and it hasn't found the end, then the pattern failed somehow
  481.     --Slightly worried this might break stuff because when you first start the node map there's only one node to check anyway
  482.     if countElements(nodesToCheck) <= 0 then return true end --Changed to true, TODO: CHANGE BACK
  483.     --The values of this function aren't really that important because the function is mainly to edit the node map, not to return a value
  484.     local nodes,hasFoundEnd,nodesToCheck = getNeighborNodes(nodeMap,node,endingPoint,nodesToCheck)
  485.     if hasFoundEnd then return true end
  486.     --Gets a node from nodesToCheck
  487.     --This gets the node at the smallest function value
  488.     --TODO: if there is an empty table at a certain function value, this will definitely break stuff
  489.     --local tempNode = table.remove(nodesToCheck[math.min(unpack(getKeys(nodesToCheck)))])
  490.     --for k,v in pairs(nodes) do
  491.         --if buildNodeMap(nodeMap,v,endingPoint,nodesToCheck) then return true end
  492.     --end
  493.     --return false
  494.     local tempNode,nodesToCheck = getNodeToCheck(nodesToCheck)
  495.     if printDebug then print(" ",textutils.serialise(tempNode,{compact=true,allow_repetitions=true})) end
  496.     if not tempNode then return false end
  497.     return buildNodeMap(nodeMap,tempNode,endingPoint,nodesToCheck,printDebug)
  498. end
  499. --Glorified wrapper for buildNodeMap
  500. --@Arg Pattern pattern: The pattern to build the nodeMap off of
  501. --@Arg Vector2D startingPoint: The starting point to pathfind from
  502. --@Arg Vector2D endingPoint: The ending point to pathfind towards
  503. --@Returns boolean success, NodeMap nodeMap: The completed nodeMap, and whether it was successful or not
  504. function generateNodeMap(pattern,startingPoint,endingPoint)
  505.     local nodeMap = {}
  506.     local nodesToCheck = {}
  507.     local validStartingPoint = false
  508.     for i=1,#pattern do
  509.         nodeMap[i] = {}
  510.         for j=1,#pattern[i] do
  511.             if i==startingPoint[2] and j == startingPoint[1] then
  512.                 validStartingPoint = {x=j,y=i,
  513.                     f=math.abs(j - endingPoint[1])+math.abs(i - endingPoint[2]),
  514.                     g = 0,
  515.                     h = math.abs(j - endingPoint[1])+math.abs(i - endingPoint[2])}
  516.                 nodeMap[i][j] = validStartingPoint
  517.             else
  518.                 nodeMap[i][j] = pattern[i][j]
  519.             end
  520.         end
  521.     end
  522.     local nodes,hasFoundEnd,nodesToCheck = getNeighborNodes(nodeMap,validStartingPoint,endingPoint,nodesToCheck)
  523.     if not validStartingPoint then return false, {}, print("No valid starting point") end
  524.     local success = buildNodeMap(nodeMap,validStartingPoint,endingPoint,nodesToCheck)
  525.     return success, nodeMap
  526. end
  527. --Reads the finished node map to get the path from the start to the end (but in reverse order because thats more efficient)
  528. --@Arg Pattern pattern: The pattern to be used for pathfinding
  529. --@Arg Vector2D pos: The ending position to navigate towards
  530. --@Arg TurtleData this: The information about the turtle, which is used for the starting point
  531. --@Returns table moves: The list of moves, in reverse order, of the path to the end
  532. --@Returns boolean false, string errMsg: If it could not pathfind towards the end
  533. function getMovesToPos(pattern,pos,this)
  534.     local success, nodeMap = generateNodeMap(pattern, {this.pos.x,this.pos.y}, pos)
  535.     if not success then return false, "Could not create a node map" end --Remove if false to go back to old conditions
  536.     local moves = {}
  537.     --Starts at the end
  538.     local currentNode = nodeMap[pos[2]][pos[1]]
  539.     --While the current node still has a parent (the first node obviously doesnt have a parent)
  540.     while currentNode.p do
  541.         table.insert(moves,currentNode.r)
  542.         --Moves on to the parent node of the previously selected node
  543.         currentNode = nodeMap[currentNode.p[2]][currentNode.p[1]]
  544.     end
  545.     return moves
  546. end
  547. --Gets the next move using a snail algorithm, which is sometimes unsuccessful
  548. --@Arg Pattern pattern: The pattern to get the next move from
  549. --@Arg TurtleData this: information about the turtle
  550. --@Arg Vector2D endingPoint: The endingPoint of the pattern
  551. --@OptionalArg table moveList: Honestly idk what I was doing with this and it didnt work when i was creating it so dont use
  552. --@OptionalArg string mode: Used for the moveList bs which i still dont understand
  553. --@Returns boolean false: If no move could be found
  554. --@Returns table moves: The moves to the ending point in reverse order, if the pattern has been fully completed
  555. --@Returns number move: The next move to take, as determined by the snail algorithm
  556. function getNextMove(pattern,this,endingPoint,moveList,mode)
  557.     --If there are no lowercase (unexplored) tiles then tries to pathfind to the end
  558.     if countElements(pattern, function(str) return type(str) == "string" and string.match(str,"%l") end) <= 0 then
  559.         return getMovesToPos(pattern,endingPoint,this)
  560.     end
  561.     if mode == "moveList" then
  562.         if type(moveList) ~= "table" or #moveList <= 0 then return false
  563.         else return table.remove(moveList) end
  564.     end
  565.     --Otherwise, gets the next move based on a spiral algorithm
  566.     --Not sure how efficient spiral is, might want to consider a new one
  567.     local moveValues = {}
  568.     local highestMoveValue = -1
  569.     --i is not absolute rotation, but rather localized rotation
  570.     --i is how many right turns the turtle would have to make to follow that path
  571.     for i=0,3 do
  572.         local v = rotToXY(this.rot+i)
  573.         local row = pattern[this.pos.y+v[2]]
  574.         local char
  575.         if row then char = row[this.pos.x+v[1]] end
  576.         char = char or " "
  577.         --If char is lowercase (unexplored), then turtle will really want to go there
  578.         if string.match(char,"%l") then moveValues[i] = 1
  579.         --If char is uppercase (explored), then turtle will only go there if there's no other options
  580.         elseif string.match(char,"%u") then moveValues[i] = 0
  581.         --If char is not alphanumeric (valid), then returns -1 (turtle will not ever try to travel there)
  582.         else moveValues[i] = -1 end
  583.         highestMoveValue = math.max(highestMoveValue,moveValues[i])
  584.         --print(i,moveValues[i])
  585.     end
  586.     --If there are no valid moves at all, (highest value found is -1), then no moves will be selected
  587.     if highestMoveValue < 0 then return false end
  588.     --for i=0,3 do
  589.         --if moveValues[i] >= highestMoveValue then return (this.rot+i)%4 end
  590.     --end
  591.     --return false
  592.    
  593.     --0 = turtle keeps going in same direction, which turtle is biased towards
  594.     if moveValues[0] >= highestMoveValue then return (this.rot+0)%4 end
  595.     --1 = turtle turns right, which turtle will prefer over going back or left
  596.     if moveValues[1] >= highestMoveValue then return (this.rot+1)%4 end
  597.     --3 = turtle turns left, which turtle will prefer over turning around
  598.     if moveValues[3] >= highestMoveValue then return (this.rot+3)%4 end
  599.     --2 = last case scenario, where turtle will turn around. Turtle tries to avoid doing this, only will do if better than all other options
  600.     if moveValues[2] >= highestMoveValue then return (this.rot+2)%4 end
  601.     return false
  602. end
  603. --Recursively will check to see if neighbors are traversable
  604. --@Arg Pattern patternValidator: The pattern validator to be updated
  605. --@Arg Vector2D pos: The position whose neighbors will get checked
  606. --@Arg table moveList: Does nothing really, so just put in {}
  607. local function checkNeighbors(patternValidator,pos,moveList)
  608.     for i=0,3 do --For each of the 4 directions
  609.         local v = rotToXY(i)
  610.         v = {pos[1]+v[1],pos[2]+v[2]}
  611.         local row = patternValidator[v[2]]
  612.         local char
  613.         if row then char = row[v[1]] end --Gets the character at the position
  614.         char = char or " "
  615.         if string.match(char,"%w") then
  616.             --If the character is traversable, replaces it with "-" to show that the patternValidator has found the character
  617.             patternValidator[v[2]][v[1]] = "-"
  618.             --Adds the character to the move list for later usage
  619.             table.insert(moveList,i)
  620.             --Recursively checks the neighbors of the character that was just validated
  621.             checkNeighbors(patternValidator,v,moveList)
  622.         end
  623.     end
  624. end
  625.  
  626. --Checks to see if the pattern is traversable
  627. --@Arg Pattern pattern: The pattern to be validated if it is possible to traverse
  628. --@Arg Vector2D startPos: The starting position of the validation check
  629. --@Returns boolean isValid, table moveList: If the pattern was valid, + the moveList bs that doesnt ever get used
  630. local function validatePattern(pattern,startPos)
  631.     local patternValidator = copyTable(pattern)
  632.     local moveList = {}
  633.     --Copies the table because it gets modified during validation
  634.     checkNeighbors(patternValidator,startPos,moveList)
  635.     --If there are still "unexplored" tiles left after validation, means that there are positions that are unable to be reached from the start pos
  636.     --Which will mean that the pattern will break stuff
  637.     return countElements(patternValidator,function(str) return type(str) == "string" and string.match(str,"%w") end) <= 0, reverseTable(moveList) --you want this less than 0, not more than 0 dummy
  638. end
  639. --Takes pattern and turns it into 2d array of chars
  640. --b = ending point
  641. --a = starting point, or ending point if b is not found
  642. --Pattern = name of pattern defined in the patterns folder
  643. --  Absolute path would look something like:  "patterns/<pattern>.txt"
  644. --@Arg string pattern: The file path to load the pattern from, within the patterns folder. Don't include the extension .txt -> "patterns/<pattern>.txt"
  645. --@Returns any nil, string errMsg: If loading the pattern failed in any way
  646. --@Returns Pattern serializedPattern, number width, number height, Vector2D startingPoint, Vector2D endingPoint, table moveList: The pattern and relevant information
  647. function loadPattern(pattern)
  648.     if not pattern then return nil,"Pattern was not specified" end
  649.     if not fs.exists("patterns/"..pattern..".txt") then return nil,"patterns/"..pattern..".txt does not exist" end
  650.     local file = fs.open("patterns/"..pattern..".txt","r")
  651.     local data = file.readAll()
  652.     file.close()
  653.     local serializedPattern = {}
  654.     local splitData = split(data,"\n")
  655.     local height = #splitData
  656.     if height <= 0 then return nil, "Pattern has no height and won't be defined" end
  657.     local width = 0
  658.     local endingPoint = nil
  659.     local startingPoint = nil
  660.     for k,v in pairs(splitData) do
  661.         --if #v <= 0 then return nil,"Row must have characters within it" end
  662.         local row = {}
  663.         width = math.max(width,#v)
  664.         local hasMoveableCharacter = false
  665.         for i=1,#v do
  666.             local char = string.sub(v,i,i)
  667.             if string.lower(char) == "a" then
  668.                 if startingPoint then return nil,"You may only have one starting point defined, dummy" end
  669.                 startingPoint = {i,k}
  670.                 table.insert(row,"a")
  671.                 hasMoveableCharacter = true
  672.             elseif string.lower(char) == "b" then
  673.                 if endingPoint then return nil,"Only up to one ending point is allowed" end
  674.                 endingPoint = {i,k}
  675.                 table.insert(row,"b")
  676.                 hasMoveableCharacter = true
  677.             elseif string.match(char,"%a") then
  678.                 table.insert(row,"x")
  679.                 hasMoveableCharacter = true
  680.             else
  681.                 table.insert(row," ")
  682.             end
  683.         end
  684.         --if not hasMoveableCharacter then return nil, "Row has no moveable characters" end
  685.         table.insert(serializedPattern,row)
  686.     end
  687.     if not startingPoint then return nil,"No starting point found" end
  688.     local success,moveList = validatePattern(serializedPattern,startingPoint)
  689.     if not success then return nil,"Pattern validation failed" end
  690.     endingPoint = endingPoint or startingPoint
  691.     return serializedPattern,width,height,startingPoint,endingPoint,moveList
  692. end
  693. --Prints pattern with fancy colors and stuff idk
  694. --@Arg Pattern pattern: The pattern to print
  695. --@Arg number width: The width of the pattern, which is important for knowing if the pattern will go offscreen
  696. --@Arg number height: The height of the pattern
  697. --@OptionalArg TurtleData this: The turtle data, which is used to show the turtle's position and rotation within the pattern
  698. function printPattern(pattern,width,height,this)
  699.     if type(pattern) == "string" then pattern,width,height = loadPattern(pattern) end
  700.     if type(pattern) ~= "table" then
  701.         term.setTextColor(colors.red)
  702.         print("Invalid Pattern")
  703.         return
  704.     end
  705.     local xOffset,yOffset = 0,0
  706.     term.setTextColor(colors.black)
  707.     local dimX,dimY = term.getSize()
  708.     if height > dimY and type(this) == "table" then
  709.         yOffset = math.floor(dimY/2)-this.pos.y
  710.     end
  711.     if width > dimX and type(this) == "table" then
  712.         xOffset = math.floor(dimX/2)-this.pos.x
  713.     end
  714.     for i=1,#pattern do
  715.         local row = pattern[i]
  716.         for j=1,width do
  717.             term.setCursorPos(j+xOffset,i+yOffset)
  718.             local char = row[j]
  719.             char = char or " "
  720.             if string.match(char,"%u") then term.setBackgroundColor(colors.lightGray)
  721.             elseif string.match(char,"%l") then term.setBackgroundColor(colors.lime)
  722.             else term.setBackgroundColor(colors.gray) end
  723.             term.write(string.match(char,"[ab]") or " ")
  724.         end
  725.     end
  726.     if this and this.pos and this.rot then
  727.         term.setCursorPos(this.pos.x+xOffset,this.pos.y+yOffset)
  728.         term.setBackgroundColor(colors.yellow)
  729.         local chars = {"^",">","v","<"}
  730.         term.write(chars[this.rot+1])
  731.     end
  732.     term.setTextColor(colors.white)
  733.     term.setBackgroundColor(colors.black)
  734.     --term.setCursorPos(1,1)
  735. end
  736. --Mines a pattern using the snail algorithm
  737. --@Arg Pattern pattern: the pattern to mine
  738. --@Arg number width: The width of the pattern [this is here to you can call mine(loadPattern(patternPath),mode,slowMode)]
  739. --@Arg number height: The height of the pattern
  740. --@Arg Vector2D startPos: The starting position to mine from
  741. --@Arg Vector2D endPos: The ending position to finish at
  742. --@Arg table moveList: Irrelevant, but kept here to make it easy to plug in
  743. --@OptionalArg string mode: Whether to mine in "xy" or "xz"
  744. --@OptionalArg boolean slowMode: If true, it will wait for a key press before moving a block
  745. --@Returns boolean success, TurtleData this: Whether the pattern was mined successfully, and the data about the turtle
  746. function mine(pattern,width,height,startPos,endPos,moveList,mode,slowMode)
  747.     if type(pattern) == "string" then pattern,width,height,startPos,endPos = loadPattern(pattern) end
  748.     if type(pattern) ~= "table" then return false end
  749.     if type(mode) ~= "string" then mode = "xy" else mode = mode end
  750.     local this = {rot=0,pos={},horizRot=0}
  751.     this.pos.x, this.pos.y = startPos[1],startPos[2]
  752.     local move = getNextMove(pattern,this,endPos,moveList)
  753.     if string.lower(mode) == "xy" then
  754.         turt.dig()
  755.         turt.forward()
  756.     else
  757.         turt.digDown()
  758.         turt.down()
  759.     end
  760.     pattern = copyTable(pattern) --IMPORTANT, so you can reuse the pattern you put in
  761.     pattern[this.pos.y] = pattern[this.pos.y] or {}
  762.     pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " "
  763.     pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
  764.     term.clear()
  765.     printPattern(pattern,width,height,this)
  766.     while move do
  767.         if slowMode and type(slowMode) == "boolean" then os.pullEvent("key") end
  768.         if type(move) == "table" then
  769.             if string.lower(mode) == "xy" then
  770.                 while #move >0 do
  771.                     doMoveXY(table.remove(move),this,pattern)
  772.                     printPattern(pattern,width,height,this)
  773.                 end
  774.                 stats.add("Patterns Mined",1)
  775.                 return true,this
  776.             else
  777.                 while #move > 0 do
  778.                     doMove(table.remove(move),this,pattern)
  779.                     printPattern(pattern,width,height,this)
  780.                 end
  781.                 stats.add("Patterns Mined",1)
  782.                 return true,this
  783.             end
  784.         elseif tonumber(move) then
  785.             if string.lower(mode) == "xy" then
  786.                 doMoveXY(move,this,pattern)
  787.             else
  788.                 doMove(move,this,pattern)
  789.             end
  790.         else
  791.             return false,this
  792.         end
  793.         move = getNextMove(pattern,this,endPos,moveList)
  794.         --term.clear()
  795.         --term.setCursorPos(1,12) --For debug
  796.         --print(move) --for debug
  797.         --print("pos,",this.pos.x, this.pos.y,this.rot,this.horizRot)
  798.         term.clear()
  799.         printPattern(pattern,width,height,this)
  800.     end
  801.     return false,this
  802. end
  803. --Mines a pattern using a cheap approximation of a hamiltonian path
  804. --@Arg Pattern pattern: the pattern to mine
  805. --@Arg number width: The width of the pattern [this is here to you can call mine(loadPattern(patternPath),mode,slowMode)]
  806. --@Arg number height: The height of the pattern
  807. --@Arg Vector2D startPos: The starting position to mine from
  808. --@Arg Vector2D endPos: The ending position to finish at
  809. --@Arg table moveList: Irrelevant, but kept here to make it easy to plug in
  810. --@OptionalArg string mode: Whether to mine in "xy" or "xz"
  811. --@OptionalArg boolean slowMode: If true, it will wait for a key press before moving a block
  812. --@OptionalArg boolean simulationOnly: If true, it won't actually mine any blocks, but will still print the pattern for usage
  813. --@Returns boolean success, TurtleData this: Whether the pattern was mined successfully, and the data about the turtle
  814. function mineHamilton(pattern,width,height,startPos,endPos,moveList,mode,slowMode,simulationOnly)
  815.     if type(pattern) == "string" then pattern,width,height,startPos,endPos = loadPattern(pattern) end
  816.     if type(pattern) ~= "table" then return false end
  817.     if type(mode) ~= "string" then mode = "xy" else mode = mode end
  818.     local this = {rot=0,pos={},horizRot=0}
  819.     this.pos.x,this.pos.y = startPos[1],startPos[2]
  820.     local map,startPos = generateMapFromPattern(pattern)
  821.     --While there still is shit to be searched
  822.     local x,y = term.getSize()
  823.     local parent = term.current()
  824.     local wndw = window.create(parent,2,2,x-2,y-2)
  825.     width,height = #map[1],#map
  826.     term.redirect(wndw)
  827.     while countElements(map,function(item) return tonumber(item) and tonumber(item) > 0 end) > 0 do
  828.         local moves = getHamiltonianPath(map,{this.pos.x,this.pos.y})
  829.         moves = reverseTable(moves)
  830.         if #moves <= 0 then
  831.             local target = getTarget(map,function(item) return tonumber(item) and tonumber(item) > 0 end)
  832.             if not target then
  833.                 term.redirect(parent)
  834.                 return false,this
  835.             end
  836.             moves = getMovesToPos(pattern,target,this)
  837.         end
  838.         if not moves or #moves <= 0 then
  839.             term.redirect(parent)
  840.             return false,this
  841.         end
  842.         if type(simulationOnly) == "boolean" and simulationOnly then
  843.             while #moves > 0 do
  844.                 simulateMove(table.remove(moves),this,pattern)
  845.                 if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
  846.                 term.clear()
  847.                 printPattern(pattern,width,height,this)
  848.             end
  849.         elseif string.lower(mode) == "xy" then
  850.             while #moves > 0 do
  851.                 doMoveXY(table.remove(moves),this,pattern)
  852.                 if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
  853.                 term.clear()
  854.                 printPattern(pattern,width,height,this)
  855.             end
  856.         else
  857.             while #moves > 0 do
  858.                 doMove(table.remove(moves),this,pattern)
  859.                 if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
  860.                 term.clear()
  861.                 printPattern(pattern,width,height,this)
  862.             end
  863.         end
  864.         term.clear()
  865.         printPattern(pattern,width,height,this)
  866.     end
  867.     local moves = getMovesToPos(pattern,endPos,this)
  868.     if type(simulationOnly) == "boolean" and simulationOnly then
  869.         while #moves > 0 do
  870.             simulateMove(table.remove(moves),this,pattern)
  871.             term.clear()
  872.             printPattern(pattern,width,height,this)
  873.             if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
  874.         end
  875.     elseif string.lower(mode) == "xy" then
  876.         while #moves <= 0 do
  877.             doMoveXY(table.remove(moves),this,pattern)
  878.             term.clear()
  879.             printPattern(pattern,width,height,this)
  880.             if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
  881.         end
  882.     else
  883.         while #moves > 0 do
  884.             doMove(table.remove(moves),this,pattern)
  885.             term.clear()
  886.             printPattern(pattern,width,height,this)
  887.             if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
  888.         end
  889.     end
  890.     term.redirect(parent)
  891.     return true, this
  892. end
Advertisement
Add Comment
Please, Sign In to add comment