minecraft-cc-tools/robot.lua
2024-05-08 20:45:08 +02:00

114 lines
2.0 KiB
Lua

-- robot api
local api = {}
api.create = function()
local state = {
y = 0,
x = 0,
z = 0,
-- | BACKWARD | LEFT | RIGHT
dir = 'FORWARD'
}
local mutateRobotPosition = function(isBackward)
local incValue = 1
if isBackward then invValue = -1 end
if dir == 'FORWARD' then
state.z = state.z + incValue
elseif dir == 'BACKWARD' then
state.z = state.z - incValue
elseif dir == 'LEFT' then
state.x = state.x - incValue
elseif dir == 'RIGHT' then
state.x = state.x + incValue
end
end
local robot = {}
robot.forward = function()
local ok, err = turtle.forward()
if ok then
mutateRobotPosition(false)
end
return ok, err
end
robot.backward = function()
local ok, err = turtle.back()
if ok then
mutateRobotPosition(true)
end
return ok, err
end
robot.up = function()
local ok, err = turtle.up()
if ok then
state.y = state.y + 1
end
return ok, err
end
robot.down = function()
local ok, err = turtle.down()
if ok then
state.y = state.y - 1
end
return ok, err
end
robot.turnLeft = function()
local ok, err = turtle.turnLeft()
if ok then
if state.dir == 'FORWARD' then
state.dir = 'LEFT'
elseif state.dir == 'LEFT' then
state.dir = 'BACKWARD'
elseif state.dir == 'RIGHT' then
state.dir = 'FORWARD'
elseif state.dir == 'BACKWARD' then
state.dir = 'RIGHT'
end
end
return ok, err
end
robot.turnRight = function()
local ok, err = turtle.turnRight()
if ok then
if state.dir == 'FORWARD' then
state.dir = 'RIGHT'
elseif state.dir == 'LEFT' then
state.dir = 'FORWARD'
elseif state.dir == 'RIGHT' then
state.dir = 'BACKWARD'
elseif state.dir == 'BACKWARD' then
state.dir = 'LEFT'
end
end
return ok, err
end
robot.getState = function()
return state
end
return robot
end
return api