Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --Turt api to replace the default turtle api for cc turtles (turt api logs stats, and has some edge cases improved)
- if not turt then os.loadAPI("apis/turt.lua") end
- --Documentation API to let people get method summaries easier
- if not docs then os.loadAPI("apis/docs.lua") end
- --Type registry
- local types = {
- ["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"},
- ["NodeMap"]={colors.orange,"A 2D array of Nodes that are used for pathfinding"},
- ["Node"]={colors.brown,"Used for pathfinding, this stores A* function values as well as other data"},
- ["Map"]={colors.orange,"A map of 0s and 1s used for approximating Hamiltonian paths"},
- ["TurtleData"]={colors.brown,"Stores turtle data such as position, horizontal rotation, and pathfinding rotation"}
- }
- for k,v in pairs(types) do
- docs.registerType(k,v[1],v[2])
- end
- --Seperates a string into a table by a seperator character
- --@Arg string input: The input string to be split
- --@OptionalArg string sep: The character, or character class to seperate the string by
- --@Returns table splitString: A list of strings that got seperated
- local function split(input,sep)
- sep = sep or "%s"
- local t = {}
- for str in string.gmatch(input,"([^"..sep.."]+)") do
- table.insert(t,str)
- end
- return t
- end
- --Recursively counts the number of specific elements inside a table
- --@Arg table array: The table to search through
- --@OptionalArg function filter: A function that returns true if the element should be counted, or false otherwise
- --@Returns number count: The number of elements that were found
- local function countElements(array,filter)
- local count = 0
- for k,v in pairs(array) do
- if type(v) ~= "table" then
- if type(filter) ~= "function" or filter(v) then
- count = count+1
- end
- else
- count = count+countElements(v,filter) --If element is a table, then the function will recursively count the elements inside the table
- end
- end
- return count
- end
- --Copies a table
- --@Arg table tab: The table to be copied
- --@Returns table t: A copy of the table inputted
- local function copyTable(tab)
- local t = {}
- for k,v in pairs(tab) do
- if type(v) == "table" then
- t[k] = copyTable(v)
- else
- t[k] = v
- end
- end
- return t
- end
- --Reverses tables, useful for moving along a table
- --@Arg table tab: The table in forward order. Should have integer keys
- --@Returns table t: The same table, in reverse order.
- local function reverseTable(tab)
- local t = {}
- while #tab > 0 do
- table.insert(t,table.remove(tab))
- end
- --for k,v in ipairs(tab) do
- --t[#tab-k+1] = v
- --end
- return t
- end
- --Returns a list of keys in a table
- --@Arg table tab: The table to retrieve the keys from
- --@Returns table t: A list of the keys of the original table
- local function getKeys(tab)
- local t = {}
- for k,v in pairs(tab) do
- table.insert(t,k)
- end
- return t
- end
- --Takes a rotation and turns it into a vector
- --Rotation in this program is defined as 0 being "up", 1 being right, 2 being down, and 3 being left
- --@OptionalArg number rot: The rotation, from 0-3, to be turned into a vector
- --@Returns Vector2D v: A vector with magnitude 1 that represents the rotation
- function rotToXY(rot)
- rot = rot or 0
- rot = rot%4
- return {math.floor(math.sin(math.pi*rot/2)+0.5),-math.floor(math.cos(math.pi*rot/2)+0.5)}
- end
- --Gets the first target found from a map
- --@Arg Map map: The map to search for a valid target
- --@OptionalArg function filter: The filter function to determine whether an element is a valid target or not
- --@Returns Vector2D v: The location of a possible target in {x,y}
- --@Returns boolean false: If no target was found
- local function getTarget(map,filter)
- for k,v in pairs(map) do
- for j,w in pairs(v) do
- if type(filter) ~= "function" or filter(w) then return {j,k} end
- end
- end
- return false
- end
- --Updates the turtle's position based on its current pathfinding rotation
- --@Arg TurtleData this: the turtle information to be updated
- --@OptionalArg number amount: How much the turtle should move
- local function updatePos(this,amount)
- amount = amount or 1
- local v = rotToXY(this.rot)
- this.pos.x = this.pos.x+amount*v[1]
- this.pos.y = this.pos.y+amount*v[2]
- end
- --Safer way of getting elements
- --@Arg table matrix: A 2D table to get the element from
- --@Arg number x: The first index of the matrix to search
- --@Arg number y: the second index of the matrix to search
- --@OptionalArg any default: What to return if the element does not exist or if it fails the filter
- --@OptionalArg function filterFunction: Filters the matrix element, possibly returning the default if it fails
- --@Returns any element: The matrix element found
- --@Returns any default: The default value if the element could not be found or if it failed the filter
- function getMatrixElement(matrix,x,y,default,filterFunction)
- if type(matrix) ~= "table" or type(matrix[x]) ~= "table" or not matrix[x][y] then return default end
- if type(filterFunction) == "function" then
- return filterFunction(matrix[x][y],default,x,y)
- else
- return matrix[x][y]
- end
- end
- --Safer way of setting elements
- --@Arg table matrix: The 2d table to be updated
- --@Arg number x: The first index of the matrix to edit
- --@Arg number y: The second index of the matrix to edit
- --@Arg any element: The new data value of the matrix at the position
- function setMatrixElement(matrix,x,y,element)
- if type(matrix) ~= "table" then matrix = {} end
- if type(matrix[x]) ~= "table" then matrix[x] = {} end
- matrix[x][y] = element
- end
- --Does cheap digs without moving to them
- --@Arg Pattern pattern: The pattern to use to decide whether the turtle should mine a specific block
- --@Arg TurtleData this: Information about the turtle such as its position
- --@OptionalArg boolean skipDigging: Whether the function should not actually interact with the world, but only update the pattern
- --@Returns table digsDone: A list of rotations of the directions that the turtle mined
- local function doCheapDigsXY(pattern,this,skipDigging)
- local dirs = {
- rotToXY(this.horizRot),
- rotToXY(0),
- rotToXY(1)
- }
- digsDone = {}
- for k,v in pairs(dirs) do
- 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)
- if string.match(char,"%l") then
- if not skipDigging then
- local j = this.horizRot
- if k == 1 then
- turt.dig()
- elseif k == 2 then
- turt.digUp()
- j = 0
- elseif k == 3 then
- turt.digDown()
- j=1
- end
- end
- table.insert(digsDone,j)
- setMatrixElement(pattern,this.pos.y+v[2],this.pos.x+v[1],string.upper(char))
- end
- end
- return digsDone
- end
- --Does cheap digs without moving to them
- --@Arg Pattern pattern: The pattern to use to decide whether the turtle should mine a specific block
- --@Arg TurtleData this: Information about the turtle such as its position
- --@OptionalArg boolean skipDigging: Whether the function should not actually interact with the world, but only update the pattern
- --@Returns table digsDone: A list of rotations of the directions that the turtle mined
- local function doCheapDigs(pattern,this,skipDigging)
- v = rotToXY(this.rot)
- 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)
- if string.match(char,"%l") then
- if not skipDigging then
- turt.dig()
- end
- setMatrixElement(pattern,this.pos.y+v[2],this.pos.x+v[1],string.upper(char))
- return {this.rot}
- end
- end
- --Patterns are 2d arrays of characters
- --Lowercase characters are valid paths, all others are either already visited or invalid
- --The maps used here are a matrix of 0 and 1s
- --@Arg Pattern pattern: The serialized pattern to generate the map from
- --@Returns Map map, Vector2D startPos: The map and the starting position for the turtle
- function generateMapFromPattern(pattern)
- local height = 0
- local width = 0
- local startPos = {} --In horizontal coordinates, of course
- for k,v in ipairs(pattern) do
- local rowWidth = 0
- for j,w in ipairs(v) do
- if type(w) == "string" and string.match(w,"%l") then
- rowWidth = j
- height = k
- end
- if type(w) == "string" and string.match(w,"[aA]") then
- startPos = {j,k}
- end
- end
- width = math.max(rowWidth,width)
- end
- local t = {}
- for i=1,height do
- local row = {}
- for j=1,width do
- if pattern[i] and type(pattern[i][j]) == "string" and string.match(pattern[i][j],"%l") then
- row[j] = 1
- else
- row[j] = 0
- end
- end
- t[i] = row
- end
- return t,startPos
- end
- --Counts the number of valid (1s) neighbors around a specific position
- --@Arg Map map: the map to be used to decide if a tile is valid
- --@Arg Vector2D pos: The x and y coordinates of the tile whose neighbors get searched
- --@Returns number count: How many neighbors were valid (1s)
- local function countValidNeighbors(map,pos)
- local count = 0
- for i=0,3 do
- local v = rotToXY(i)
- if getMatrixElement(map,pos[2]+v[2],pos[1]+v[1],0,function(element,default) return tonumber(element) or default end) > 0 then
- count = count + 1
- end
- end
- return count
- end
- --Gets the next map move
- --The function prioritizes the next node with the least number of valid neighbors (but still having at least one more neighbor to travel to)
- --As a tiebreaker, the function also prioritizes doing the least number of right turns (biased towards moving straight, and biased against going left)
- --@Arg Map map: The map of traversable and inaccessable tiles
- --@Arg Vector2D pos: The position around which to get the next move
- --@OptionalArg number lastMove: The rotation of the last move
- --@Returns number rot: The rotation to travel to, or -1 if there is no valid move
- local function getNextMapMove(map,pos,lastMove)
- lastMove = tonumber(lastMove) or 0
- setMatrixElement(map,pos[2],pos[1],0)
- local moveMap = {} --Sorting moves by their costs
- local lowestScore = 69
- for i=0,3 do
- local v = rotToXY(i)
- if getMatrixElement(map,pos[2]+v[2],pos[1]+v[1],0,function(element,default) return tonumber(element) or default end) > 0 then
- local countScore = countValidNeighbors(map,{pos[1]+v[1],pos[2]+v[2]})--Least number of neighbors (but more than 0) is preferable
- if countScore <= 0 then countScore = 4 end
- countScore = countScore*4 --Scaling countscore to make it more influential than rotation score
- local rotationScore = (i-lastMove)%4 --Least number of right turns needed to take to do the move is preferable
- moveMap[i] = countScore+rotationScore
- lowestScore = math.min(lowestScore,countScore+rotationScore)
- end
- end
- for i=0,3 do
- if moveMap[i] then
- if moveMap[i] <= lowestScore then return i end
- end
- end
- return -1
- end
- --Idea stolen from stackexchange
- --Basically, prioritizing travelling to nodes with the least number of connecting nodes (but still with connecting nodes)
- --@Arg Map map: The map to generate the path from
- --@Arg Vector2D startPos: The starting position to generate the path from
- --@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)
- local function getHamiltonianPath(map,startPos)
- local moves = {}
- local pos = startPos
- local move = getNextMapMove(map,pos,0)
- while move >= 0 do
- table.insert(moves,move)
- local v = rotToXY(move)
- pos = {pos[1]+v[1],pos[2]+v[2]}
- move = getNextMapMove(map,pos,move)
- end
- return moves
- end
- --Will move the turtle in the direction specified, but on the XY plane
- --Also updates the pattern so the tile under where the turtle is turns upper case (which means already explored)
- --@Arg number dir: The direction to move the turtle in
- --@Arg TurtleData this: Information about the turtle
- --@Arg Pattern pattern: The pattern to be updated as the turtle moves
- local function rawMoveXY(dir,this,pattern)
- dir = dir%4
- --0 means straight up, in the xy plane
- if dir == 0 then
- turt.digUp()
- turt.up()
- this.rot = 0
- updatePos(this)
- --2 means straight down
- elseif dir == 2 then
- turt.digDown()
- turt.down()
- this.rot = 2
- updatePos(this)
- --TODO: This will break stuff if the last direction mined was up or down, need to fix
- --Fixed??
- --elseif this.rot == dir then
- --turt.dig()
- --turt.forward()
- --updatePos(this)
- --else
- --turt.turnLeft(2)
- --turt.dig()
- --turt.forward()
- --this.rot = dir
- --updatePos(this)
- --end
- else
- while this.horizRot ~= dir do
- turt.turnRight()
- this.horizRot = (this.horizRot+1)%4
- end
- this.rot = this.horizRot
- turt.dig()
- turt.forward()
- updatePos(this)
- end
- pattern[this.pos.y] = pattern[this.pos.y] or {}
- pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " " --So it doesnt lose its shit
- pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
- --if map then setMatrixElement(map,this.pos.y,this.pos.x,0) end
- end
- --Same as moveXY, but on the XZ plane instead, meaning that dir=0 is 'forward' in the original reference frame
- --@Arg number dir: The direction to move the turtle in
- --@Arg TurtleData this: Information about the turtle
- --@Arg Pattern pattern: The pattern to be updated as the turtle moves
- local function rawMove(dir,this,pattern)
- dir = dir%4
- while this.rot ~= dir do
- turt.turnRight()
- this.rot = (this.rot+1)%4
- end
- turt.dig()
- turt.forward()
- updatePos(this)
- pattern[this.pos.y] = pattern[this.pos.y] or {}
- pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " " --See above
- pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
- this.horizRot = this.rot
- --if map then setMatrixElement(map,this.pos.y,this.pos.x,0) end
- end
- --"Pretends" to do a move, meaning it will only update a pattern, good for testing
- --@Arg number dir: The direction to move the turtle in
- --@Arg TurtleData this: Information about the turtle
- --@Arg Pattern pattern: The pattern to be updated as the turtle moves
- local function simulateRawMove(dir,this,pattern)
- dir = dir%4
- while this.rot ~= dir do
- --turt.turnRight()
- this.rot = (this.rot+1)%4
- end
- --turt.dig()
- --turt.forward()
- updatePos(this)
- pattern[this.pos.y] = pattern[this.pos.y] or {}
- pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " " --See above
- pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
- --if map then setMatrixElement(map,this.pos.y,this.pos.x,0) end
- end
- --Does a move in XY, with the addition of doing "cheap digs" that require no movement or rotation
- --@Arg number dir: The direction to move the turtle in
- --@Arg TurtleData this: Information about the turtle
- --@Arg Pattern pattern: The pattern to be updated as the turtle moves
- local function doMoveXY(dir,this,pattern)
- doCheapDigsXY(pattern,this,false)
- rawMoveXY(dir,this,pattern)
- doCheapDigsXY(pattern,this,false)
- end
- --Does a move, with the addition of doing "cheap digs" that require no movement or rotation
- --@Arg number dir: The direction to move the turtle in
- --@Arg TurtleData this: Information about the turtle
- --@Arg Pattern pattern: The pattern to be updated as the turtle moves
- local function doMove(dir,this,pattern)
- doCheapDigs(pattern,this,false)
- rawMove(dir,this,pattern)
- doCheapDigs(pattern,this,false)
- end
- --Simulates a move, with the addition of simulating "cheap digs" that require no movement or rotation
- --@Arg number dir: The direction to "move" the turtle in
- --@Arg TurtleData this: Information about the turtle
- --@Arg Pattern pattern: The pattern to be updated as the turtle "moves"
- --@Arg string mode: "xy" to simulate in xy, "xz" to simulate in xz
- local function simulateMove(dir,this,pattern,mode)
- if mode == "xy" then
- doCheapDigsXY(pattern,this,true)
- else
- doCheapDigs(pattern,this,true)
- end
- simulateRawMove(dir,this,pattern)
- if mode == "xy" then
- doCheapDigsXY(pattern,this,true)
- else
- doCheapDigs(pattern,this,true)
- end
- end
- --Node layout = {x=,y=,f=,g=,h=,p=[x,y],r=r}
- --Gets the new node next to the orignal node in the direction specified
- --@Arg NodeMap nodeMap: The map of nodes to be filled out
- --@Arg Node node: The parent node to be generated
- --@Arg Vector2D endingPoint: The coordinates of the ending position, for generating A* heuistics
- --@Arg number direction: The direction to generate the new node in, starting from the parent node
- --@Returns boolean false: If the tile to generate the new node in is unpassable or if the node was already generated
- --@Returns Node newNode: The new node that got created
- local function getNode(nodeMap,node,endingPoint,direction)
- --Turning direction into a vector that can be added
- local v = rotToXY(direction)
- --X and y coordinates of the new node
- local x,y = node.x+v[1],node.y+v[2]
- --Returning nil if the nodeMap already has a node at the tile, or if the tile is not valid to be traversed
- if not nodeMap[y] then return end
- if type(nodeMap[y][x]) ~= "string" or not string.match(nodeMap[y][x],"%w") then return false end
- --Calculating A* Heuristic with manhattan distance
- local h = math.abs(x - endingPoint[1]) + math.abs(y - endingPoint[2])
- --Calculating A* Cost, which is just the number of moves it takes to get to this node
- local g = node.g+1
- --Putting in parent node location
- local p = {node.x,node.y}
- --Putting in the rotation to be used by turtles
- local r = (direction)%4
- local newNode = {x=x,y=y,f=g+h,g=g,h=h,p=p,r=r}
- --nodeMap[y][x] = newNode //Got rid of this because it's moved to the getNeighborNodes function
- return newNode
- end
- --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)
- --NodeMap starts off as just a copy of the Pattern map, but as nodes get filled in, the pattern gets replaced by nodes
- --Nodes to check structure: {f value: [node1,node2,...]}
- --@Arg NodeMap nodeMap: The nodeMap to be updated
- --@Arg Node node: The parent node for the neighbors
- --@Arg Vector2D endingPoint: The ending point that is being navigated towards
- --@Arg table nodesToCheck: A list of Nodes that still have not been checked, sorted by their function value
- local function getNeighborNodes(nodeMap,node,endingPoint,nodesToCheck)
- 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
- local nodes = {}
- local hasFoundEnd = false --Has found end flag to let the nodeMap functions know when to stop
- for i=0,3 do --For each direction, gets the nodes (or nil if invalid condition as stated in previous function)
- local newNode = getNode(nodeMap,node,endingPoint,i) --Gets the node in the direction
- if newNode then
- if not nodeMap[newNode.y] then nodeMap[newNode.y] = {} end --Shouldnt need but just in case
- nodeMap[newNode.y][newNode.x] = newNode --Adds node to the nodeMap
- if newNode.h <= 0 then hasFoundEnd = true end --If h value is 0, then that node is the ending node
- table.insert(nodes,newNode) --the nodes table doesnt really get used anyway, but keeping it because why not
- 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
- table.insert(nodesToCheck[newNode.f],newNode)
- end
- end
- return nodes,hasFoundEnd,nodesToCheck
- end
- --Gets nodes to check
- --Might break if f value is ever 0 (you pathfind starting at the ending pos)
- --@Arg table nodesToCheck: A list of nodes to check, sorted by function value.
- --@Returns Node node, table nodesToCheck: If successful, returns the node with the lowest function value
- --@Returns boolean false, table nodesToCheck: If not successful, returns false
- local function getNodeToCheck(nodesToCheck)
- for k,v in pairs(nodesToCheck) do
- if type(v) == "table" and #v > 0 then return table.remove(v),nodesToCheck end
- end
- return false, nodesToCheck
- end
- --Recursively generates the node map from the pattern map until an end is found
- --@Arg NodeMap nodeMap: The nodeMap to be filled out
- --@Arg Node node: The initial node to build off of
- --@Arg Vector2D endingPoint: The position to navigate towards
- --@Arg table nodesToCheck: A list of nodes to check, sorted by function value
- --@OptionalArg boolean printDebug: Deprecated, but prints the node to be checked
- local function buildNodeMap(nodeMap,node,endingPoint,nodesToCheck,printDebug)
- if not nodeMap[endingPoint[2]] then return false end --Makes it avoid shitting itself
- --If the element at the end position is a table (node), then the function is complete
- if type(nodeMap[endingPoint[2]][endingPoint[1]]) == "table" then return true end
- --If there are no more nodes to check, and it hasn't found the end, then the pattern failed somehow
- --Slightly worried this might break stuff because when you first start the node map there's only one node to check anyway
- if countElements(nodesToCheck) <= 0 then return true end --Changed to true, TODO: CHANGE BACK
- --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
- local nodes,hasFoundEnd,nodesToCheck = getNeighborNodes(nodeMap,node,endingPoint,nodesToCheck)
- if hasFoundEnd then return true end
- --Gets a node from nodesToCheck
- --This gets the node at the smallest function value
- --TODO: if there is an empty table at a certain function value, this will definitely break stuff
- --local tempNode = table.remove(nodesToCheck[math.min(unpack(getKeys(nodesToCheck)))])
- --for k,v in pairs(nodes) do
- --if buildNodeMap(nodeMap,v,endingPoint,nodesToCheck) then return true end
- --end
- --return false
- local tempNode,nodesToCheck = getNodeToCheck(nodesToCheck)
- if printDebug then print(" ",textutils.serialise(tempNode,{compact=true,allow_repetitions=true})) end
- if not tempNode then return false end
- return buildNodeMap(nodeMap,tempNode,endingPoint,nodesToCheck,printDebug)
- end
- --Glorified wrapper for buildNodeMap
- --@Arg Pattern pattern: The pattern to build the nodeMap off of
- --@Arg Vector2D startingPoint: The starting point to pathfind from
- --@Arg Vector2D endingPoint: The ending point to pathfind towards
- --@Returns boolean success, NodeMap nodeMap: The completed nodeMap, and whether it was successful or not
- function generateNodeMap(pattern,startingPoint,endingPoint)
- local nodeMap = {}
- local nodesToCheck = {}
- local validStartingPoint = false
- for i=1,#pattern do
- nodeMap[i] = {}
- for j=1,#pattern[i] do
- if i==startingPoint[2] and j == startingPoint[1] then
- validStartingPoint = {x=j,y=i,
- f=math.abs(j - endingPoint[1])+math.abs(i - endingPoint[2]),
- g = 0,
- h = math.abs(j - endingPoint[1])+math.abs(i - endingPoint[2])}
- nodeMap[i][j] = validStartingPoint
- else
- nodeMap[i][j] = pattern[i][j]
- end
- end
- end
- local nodes,hasFoundEnd,nodesToCheck = getNeighborNodes(nodeMap,validStartingPoint,endingPoint,nodesToCheck)
- if not validStartingPoint then return false, {}, print("No valid starting point") end
- local success = buildNodeMap(nodeMap,validStartingPoint,endingPoint,nodesToCheck)
- return success, nodeMap
- end
- --Reads the finished node map to get the path from the start to the end (but in reverse order because thats more efficient)
- --@Arg Pattern pattern: The pattern to be used for pathfinding
- --@Arg Vector2D pos: The ending position to navigate towards
- --@Arg TurtleData this: The information about the turtle, which is used for the starting point
- --@Returns table moves: The list of moves, in reverse order, of the path to the end
- --@Returns boolean false, string errMsg: If it could not pathfind towards the end
- function getMovesToPos(pattern,pos,this)
- local success, nodeMap = generateNodeMap(pattern, {this.pos.x,this.pos.y}, pos)
- if not success then return false, "Could not create a node map" end --Remove if false to go back to old conditions
- local moves = {}
- --Starts at the end
- local currentNode = nodeMap[pos[2]][pos[1]]
- --While the current node still has a parent (the first node obviously doesnt have a parent)
- while currentNode.p do
- table.insert(moves,currentNode.r)
- --Moves on to the parent node of the previously selected node
- currentNode = nodeMap[currentNode.p[2]][currentNode.p[1]]
- end
- return moves
- end
- --Gets the next move using a snail algorithm, which is sometimes unsuccessful
- --@Arg Pattern pattern: The pattern to get the next move from
- --@Arg TurtleData this: information about the turtle
- --@Arg Vector2D endingPoint: The endingPoint of the pattern
- --@OptionalArg table moveList: Honestly idk what I was doing with this and it didnt work when i was creating it so dont use
- --@OptionalArg string mode: Used for the moveList bs which i still dont understand
- --@Returns boolean false: If no move could be found
- --@Returns table moves: The moves to the ending point in reverse order, if the pattern has been fully completed
- --@Returns number move: The next move to take, as determined by the snail algorithm
- function getNextMove(pattern,this,endingPoint,moveList,mode)
- --If there are no lowercase (unexplored) tiles then tries to pathfind to the end
- if countElements(pattern, function(str) return type(str) == "string" and string.match(str,"%l") end) <= 0 then
- return getMovesToPos(pattern,endingPoint,this)
- end
- if mode == "moveList" then
- if type(moveList) ~= "table" or #moveList <= 0 then return false
- else return table.remove(moveList) end
- end
- --Otherwise, gets the next move based on a spiral algorithm
- --Not sure how efficient spiral is, might want to consider a new one
- local moveValues = {}
- local highestMoveValue = -1
- --i is not absolute rotation, but rather localized rotation
- --i is how many right turns the turtle would have to make to follow that path
- for i=0,3 do
- local v = rotToXY(this.rot+i)
- local row = pattern[this.pos.y+v[2]]
- local char
- if row then char = row[this.pos.x+v[1]] end
- char = char or " "
- --If char is lowercase (unexplored), then turtle will really want to go there
- if string.match(char,"%l") then moveValues[i] = 1
- --If char is uppercase (explored), then turtle will only go there if there's no other options
- elseif string.match(char,"%u") then moveValues[i] = 0
- --If char is not alphanumeric (valid), then returns -1 (turtle will not ever try to travel there)
- else moveValues[i] = -1 end
- highestMoveValue = math.max(highestMoveValue,moveValues[i])
- --print(i,moveValues[i])
- end
- --If there are no valid moves at all, (highest value found is -1), then no moves will be selected
- if highestMoveValue < 0 then return false end
- --for i=0,3 do
- --if moveValues[i] >= highestMoveValue then return (this.rot+i)%4 end
- --end
- --return false
- --0 = turtle keeps going in same direction, which turtle is biased towards
- if moveValues[0] >= highestMoveValue then return (this.rot+0)%4 end
- --1 = turtle turns right, which turtle will prefer over going back or left
- if moveValues[1] >= highestMoveValue then return (this.rot+1)%4 end
- --3 = turtle turns left, which turtle will prefer over turning around
- if moveValues[3] >= highestMoveValue then return (this.rot+3)%4 end
- --2 = last case scenario, where turtle will turn around. Turtle tries to avoid doing this, only will do if better than all other options
- if moveValues[2] >= highestMoveValue then return (this.rot+2)%4 end
- return false
- end
- --Recursively will check to see if neighbors are traversable
- --@Arg Pattern patternValidator: The pattern validator to be updated
- --@Arg Vector2D pos: The position whose neighbors will get checked
- --@Arg table moveList: Does nothing really, so just put in {}
- local function checkNeighbors(patternValidator,pos,moveList)
- for i=0,3 do --For each of the 4 directions
- local v = rotToXY(i)
- v = {pos[1]+v[1],pos[2]+v[2]}
- local row = patternValidator[v[2]]
- local char
- if row then char = row[v[1]] end --Gets the character at the position
- char = char or " "
- if string.match(char,"%w") then
- --If the character is traversable, replaces it with "-" to show that the patternValidator has found the character
- patternValidator[v[2]][v[1]] = "-"
- --Adds the character to the move list for later usage
- table.insert(moveList,i)
- --Recursively checks the neighbors of the character that was just validated
- checkNeighbors(patternValidator,v,moveList)
- end
- end
- end
- --Checks to see if the pattern is traversable
- --@Arg Pattern pattern: The pattern to be validated if it is possible to traverse
- --@Arg Vector2D startPos: The starting position of the validation check
- --@Returns boolean isValid, table moveList: If the pattern was valid, + the moveList bs that doesnt ever get used
- local function validatePattern(pattern,startPos)
- local patternValidator = copyTable(pattern)
- local moveList = {}
- --Copies the table because it gets modified during validation
- checkNeighbors(patternValidator,startPos,moveList)
- --If there are still "unexplored" tiles left after validation, means that there are positions that are unable to be reached from the start pos
- --Which will mean that the pattern will break stuff
- 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
- end
- --Takes pattern and turns it into 2d array of chars
- --b = ending point
- --a = starting point, or ending point if b is not found
- --Pattern = name of pattern defined in the patterns folder
- -- Absolute path would look something like: "patterns/<pattern>.txt"
- --@Arg string pattern: The file path to load the pattern from, within the patterns folder. Don't include the extension .txt -> "patterns/<pattern>.txt"
- --@Returns any nil, string errMsg: If loading the pattern failed in any way
- --@Returns Pattern serializedPattern, number width, number height, Vector2D startingPoint, Vector2D endingPoint, table moveList: The pattern and relevant information
- function loadPattern(pattern)
- if not pattern then return nil,"Pattern was not specified" end
- if not fs.exists("patterns/"..pattern..".txt") then return nil,"patterns/"..pattern..".txt does not exist" end
- local file = fs.open("patterns/"..pattern..".txt","r")
- local data = file.readAll()
- file.close()
- local serializedPattern = {}
- local splitData = split(data,"\n")
- local height = #splitData
- if height <= 0 then return nil, "Pattern has no height and won't be defined" end
- local width = 0
- local endingPoint = nil
- local startingPoint = nil
- for k,v in pairs(splitData) do
- --if #v <= 0 then return nil,"Row must have characters within it" end
- local row = {}
- width = math.max(width,#v)
- local hasMoveableCharacter = false
- for i=1,#v do
- local char = string.sub(v,i,i)
- if string.lower(char) == "a" then
- if startingPoint then return nil,"You may only have one starting point defined, dummy" end
- startingPoint = {i,k}
- table.insert(row,"a")
- hasMoveableCharacter = true
- elseif string.lower(char) == "b" then
- if endingPoint then return nil,"Only up to one ending point is allowed" end
- endingPoint = {i,k}
- table.insert(row,"b")
- hasMoveableCharacter = true
- elseif string.match(char,"%a") then
- table.insert(row,"x")
- hasMoveableCharacter = true
- else
- table.insert(row," ")
- end
- end
- --if not hasMoveableCharacter then return nil, "Row has no moveable characters" end
- table.insert(serializedPattern,row)
- end
- if not startingPoint then return nil,"No starting point found" end
- local success,moveList = validatePattern(serializedPattern,startingPoint)
- if not success then return nil,"Pattern validation failed" end
- endingPoint = endingPoint or startingPoint
- return serializedPattern,width,height,startingPoint,endingPoint,moveList
- end
- --Prints pattern with fancy colors and stuff idk
- --@Arg Pattern pattern: The pattern to print
- --@Arg number width: The width of the pattern, which is important for knowing if the pattern will go offscreen
- --@Arg number height: The height of the pattern
- --@OptionalArg TurtleData this: The turtle data, which is used to show the turtle's position and rotation within the pattern
- function printPattern(pattern,width,height,this)
- if type(pattern) == "string" then pattern,width,height = loadPattern(pattern) end
- if type(pattern) ~= "table" then
- term.setTextColor(colors.red)
- print("Invalid Pattern")
- return
- end
- local xOffset,yOffset = 0,0
- term.setTextColor(colors.black)
- local dimX,dimY = term.getSize()
- if height > dimY and type(this) == "table" then
- yOffset = math.floor(dimY/2)-this.pos.y
- end
- if width > dimX and type(this) == "table" then
- xOffset = math.floor(dimX/2)-this.pos.x
- end
- for i=1,#pattern do
- local row = pattern[i]
- for j=1,width do
- term.setCursorPos(j+xOffset,i+yOffset)
- local char = row[j]
- char = char or " "
- if string.match(char,"%u") then term.setBackgroundColor(colors.lightGray)
- elseif string.match(char,"%l") then term.setBackgroundColor(colors.lime)
- else term.setBackgroundColor(colors.gray) end
- term.write(string.match(char,"[ab]") or " ")
- end
- end
- if this and this.pos and this.rot then
- term.setCursorPos(this.pos.x+xOffset,this.pos.y+yOffset)
- term.setBackgroundColor(colors.yellow)
- local chars = {"^",">","v","<"}
- term.write(chars[this.rot+1])
- end
- term.setTextColor(colors.white)
- term.setBackgroundColor(colors.black)
- --term.setCursorPos(1,1)
- end
- --Mines a pattern using the snail algorithm
- --@Arg Pattern pattern: the pattern to mine
- --@Arg number width: The width of the pattern [this is here to you can call mine(loadPattern(patternPath),mode,slowMode)]
- --@Arg number height: The height of the pattern
- --@Arg Vector2D startPos: The starting position to mine from
- --@Arg Vector2D endPos: The ending position to finish at
- --@Arg table moveList: Irrelevant, but kept here to make it easy to plug in
- --@OptionalArg string mode: Whether to mine in "xy" or "xz"
- --@OptionalArg boolean slowMode: If true, it will wait for a key press before moving a block
- --@Returns boolean success, TurtleData this: Whether the pattern was mined successfully, and the data about the turtle
- function mine(pattern,width,height,startPos,endPos,moveList,mode,slowMode)
- if type(pattern) == "string" then pattern,width,height,startPos,endPos = loadPattern(pattern) end
- if type(pattern) ~= "table" then return false end
- if type(mode) ~= "string" then mode = "xy" else mode = mode end
- local this = {rot=0,pos={},horizRot=0}
- this.pos.x, this.pos.y = startPos[1],startPos[2]
- local move = getNextMove(pattern,this,endPos,moveList)
- if string.lower(mode) == "xy" then
- turt.dig()
- turt.forward()
- else
- turt.digDown()
- turt.down()
- end
- pattern = copyTable(pattern) --IMPORTANT, so you can reuse the pattern you put in
- pattern[this.pos.y] = pattern[this.pos.y] or {}
- pattern[this.pos.y][this.pos.x] = pattern[this.pos.y][this.pos.x] or " "
- pattern[this.pos.y][this.pos.x] = string.upper(pattern[this.pos.y][this.pos.x])
- term.clear()
- printPattern(pattern,width,height,this)
- while move do
- if slowMode and type(slowMode) == "boolean" then os.pullEvent("key") end
- if type(move) == "table" then
- if string.lower(mode) == "xy" then
- while #move >0 do
- doMoveXY(table.remove(move),this,pattern)
- printPattern(pattern,width,height,this)
- end
- stats.add("Patterns Mined",1)
- return true,this
- else
- while #move > 0 do
- doMove(table.remove(move),this,pattern)
- printPattern(pattern,width,height,this)
- end
- stats.add("Patterns Mined",1)
- return true,this
- end
- elseif tonumber(move) then
- if string.lower(mode) == "xy" then
- doMoveXY(move,this,pattern)
- else
- doMove(move,this,pattern)
- end
- else
- return false,this
- end
- move = getNextMove(pattern,this,endPos,moveList)
- --term.clear()
- --term.setCursorPos(1,12) --For debug
- --print(move) --for debug
- --print("pos,",this.pos.x, this.pos.y,this.rot,this.horizRot)
- term.clear()
- printPattern(pattern,width,height,this)
- end
- return false,this
- end
- --Mines a pattern using a cheap approximation of a hamiltonian path
- --@Arg Pattern pattern: the pattern to mine
- --@Arg number width: The width of the pattern [this is here to you can call mine(loadPattern(patternPath),mode,slowMode)]
- --@Arg number height: The height of the pattern
- --@Arg Vector2D startPos: The starting position to mine from
- --@Arg Vector2D endPos: The ending position to finish at
- --@Arg table moveList: Irrelevant, but kept here to make it easy to plug in
- --@OptionalArg string mode: Whether to mine in "xy" or "xz"
- --@OptionalArg boolean slowMode: If true, it will wait for a key press before moving a block
- --@OptionalArg boolean simulationOnly: If true, it won't actually mine any blocks, but will still print the pattern for usage
- --@Returns boolean success, TurtleData this: Whether the pattern was mined successfully, and the data about the turtle
- function mineHamilton(pattern,width,height,startPos,endPos,moveList,mode,slowMode,simulationOnly)
- if type(pattern) == "string" then pattern,width,height,startPos,endPos = loadPattern(pattern) end
- if type(pattern) ~= "table" then return false end
- if type(mode) ~= "string" then mode = "xy" else mode = mode end
- local this = {rot=0,pos={},horizRot=0}
- this.pos.x,this.pos.y = startPos[1],startPos[2]
- local map,startPos = generateMapFromPattern(pattern)
- --While there still is shit to be searched
- local x,y = term.getSize()
- local parent = term.current()
- local wndw = window.create(parent,2,2,x-2,y-2)
- width,height = #map[1],#map
- term.redirect(wndw)
- while countElements(map,function(item) return tonumber(item) and tonumber(item) > 0 end) > 0 do
- local moves = getHamiltonianPath(map,{this.pos.x,this.pos.y})
- moves = reverseTable(moves)
- if #moves <= 0 then
- local target = getTarget(map,function(item) return tonumber(item) and tonumber(item) > 0 end)
- if not target then
- term.redirect(parent)
- return false,this
- end
- moves = getMovesToPos(pattern,target,this)
- end
- if not moves or #moves <= 0 then
- term.redirect(parent)
- return false,this
- end
- if type(simulationOnly) == "boolean" and simulationOnly then
- while #moves > 0 do
- simulateMove(table.remove(moves),this,pattern)
- if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
- term.clear()
- printPattern(pattern,width,height,this)
- end
- elseif string.lower(mode) == "xy" then
- while #moves > 0 do
- doMoveXY(table.remove(moves),this,pattern)
- if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
- term.clear()
- printPattern(pattern,width,height,this)
- end
- else
- while #moves > 0 do
- doMove(table.remove(moves),this,pattern)
- if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
- term.clear()
- printPattern(pattern,width,height,this)
- end
- end
- term.clear()
- printPattern(pattern,width,height,this)
- end
- local moves = getMovesToPos(pattern,endPos,this)
- if type(simulationOnly) == "boolean" and simulationOnly then
- while #moves > 0 do
- simulateMove(table.remove(moves),this,pattern)
- term.clear()
- printPattern(pattern,width,height,this)
- if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
- end
- elseif string.lower(mode) == "xy" then
- while #moves <= 0 do
- doMoveXY(table.remove(moves),this,pattern)
- term.clear()
- printPattern(pattern,width,height,this)
- if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
- end
- else
- while #moves > 0 do
- doMove(table.remove(moves),this,pattern)
- term.clear()
- printPattern(pattern,width,height,this)
- if type(slowMode) == "boolean" and slowMode then os.pullEvent("key") end
- end
- end
- term.redirect(parent)
- return true, this
- end
Advertisement
Add Comment
Please, Sign In to add comment