You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

126 lines
2.7 KiB

local robot = require('robot')
local sides = require('sides')
local nav = require('nav')
local io = require('io')
local filename, mode = ...
if not filename or not mode then
print('Usage: build <filename> <corner|center>')
print('Top of the blueprint file will be where the robot is facing')
return 1
end
---Read file line by line and split lines to characters and parse numbers
---@param f file*
---@return table grid
local function parse_file(f)
local grid = {}
local line = f:read("*l")
while line do
local index = 1
local row = {}
for c in string.gmatch(line, ".") do
if c ~= '.' and c ~= ' ' then
local n = tonumber(c)
if n then
row[index] = n
else
row[index] = 0
end
else
row[index] = 0
end
index = index + 1
end
grid[#grid + 1] = row
line = f:read("*l")
end
return grid
end
---Move the robot from the center of the grid to the top left corner
---Begins facing "up" and ends facing "up"
---@param grid table 2d array
local function move_to_corner(grid)
local x = math.floor(#grid / 2)
nav.forward(x)
robot.turnLeft()
local z = math.floor(#(grid[1]) / 2)
nav.forward(z)
robot.turnRight()
end
---Move the robot from the bottom left corner of the grid to the center
---Begins facing "up" and ends facing "up"
---@param grid table 2d array
local function move_back_to_center(grid)
local x = math.floor(#grid / 2)
nav.forward(x)
robot.turnRight()
local z = math.floor(#(grid[1]) / 2)
nav.forward(z)
robot.turnLeft()
end
---Move the robot from the bottom left corner of the grid to the center
---Begins facing "up" and ends facing "up"
---@param grid table 2d array
local function move_back_to_top_corner(grid)
nav.forward(#grid - 1)
end
---Build the blueprint
---Robot begins facing up
---@param grid table 2d array
local function build(grid)
robot.turnRight()
for _, row in ipairs(grid) do
for _, block in ipairs(row) do
if block ~= 0 then
robot.select(block)
robot.placeDown(sides.down)
end
nav.forward(1)
end
robot.turnRight()
nav.forward(1)
robot.turnRight()
nav.forward(#row)
robot.turnAround()
end
robot.turnLeft()
nav.forward()
end
local file = io.open(filename, 'r')
if not file then
print('File not found')
return 2
end
local grid = parse_file(file)
if mode == 'center' then
move_to_corner(grid)
end
build(grid)
if mode == 'center' then
move_back_to_center(grid)
else
move_back_to_top_corner(grid)
end
file:close()