-- robot api local api = {} local function createDefaultState() return { y = 0, x = 0, z = 0, -- | BACKWARD | LEFT | RIGHT dir = 'FORWARD' } end api.create = function(state) state = state or createDefaultState() local mutateRobotPosition = function(isBackward) local incValue = 1 if isBackward then invValue = -1 end if state.dir == 'FORWARD' then state.z = state.z + incValue elseif state.dir == 'BACKWARD' then state.z = state.z - incValue elseif state.dir == 'LEFT' then state.x = state.x - incValue elseif state.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.back = function() local ok, err = turtle.back() if ok then mutateRobotPosition(true) end return ok, err end robot.backward = robot.back 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