Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- wireless_turtle.lua
- local modem = peripheral.find("modem")
- if not modem then
- print("No modem found")
- return
- end
- local basePort = 2469
- modem.open(basePort)
- local currentTask = nil
- local shouldStop = false
- local turtleId = tostring(math.random(1000, 9999)) -- Generate a random 4-digit ID
- local function advertise()
- while true do
- modem.transmit(basePort, basePort, {command = "pong", id = turtleId})
- sleep(2) -- Advertise every 2 seconds
- end
- end
- local function checkStop()
- if shouldStop then
- error("Stopped")
- end
- end
- local function digHeight(height)
- if height > 0 then
- for i = 1, height - 1 do
- turtle.digUp()
- if i < height - 1 then
- turtle.up()
- end
- end
- for i = 1, height - 2 do
- turtle.down()
- end
- elseif height < 0 then
- for i = 1, -height do
- turtle.digDown()
- if i < -height then
- turtle.down()
- end
- end
- for i = 1, -height - 1 do
- turtle.up()
- end
- end
- turtle.dig() -- Always dig forward
- end
- local function smartmine(length, width, height)
- currentTask = "Mining"
- shouldStop = false
- local direction = 1 -- 1 for forward, -1 for backward
- for w = 1, width do
- for l = 1, length do
- checkStop()
- digHeight(height)
- if l < length then
- turtle.forward()
- end
- end
- if w < width then
- if direction == 1 then
- turtle.turnRight()
- else
- turtle.turnLeft()
- end
- digHeight(height)
- turtle.forward()
- if direction == 1 then
- turtle.turnRight()
- else
- turtle.turnLeft()
- end
- direction = -direction
- end
- end
- currentTask = nil
- modem.transmit(basePort, basePort, {command = "miningComplete", id = turtleId})
- end
- local function handleCommands()
- while true do
- local event, side, channel, replyChannel, message, distance = os.pullEvent("modem_message")
- if channel == basePort and type(message) == "table" then
- if message.id == turtleId or message == "ping" then
- if message.command == "smartmine" then
- parallel.waitForAny(
- function() smartmine(message.length, message.width, message.height) end,
- handleCommands
- )
- elseif message.command == "stop" then
- shouldStop = true
- currentTask = "Stopped"
- modem.transmit(basePort, basePort, {command = "stopped", id = turtleId})
- elseif message.command == "stats" then
- modem.transmit(basePort, basePort, {command = "stats", id = turtleId, fuel = turtle.getFuelLevel(), task = currentTask or "Idle"})
- elseif message == "ping" then
- modem.transmit(basePort, basePort, {command = "pong", id = turtleId})
- end
- end
- end
- end
- end
- print("Turtle ID: " .. turtleId)
- parallel.waitForAll(advertise, handleCommands)
Advertisement
Add Comment
Please, Sign In to add comment