CCCPaste

playerDetector

-- player_detector70 --
-- CONFIGURATION --
local detectionRange = 70      -- Detection range in blocks
local redstoneSide = "front"   -- Side where redstone signal is sent
local checkDelay = 2           -- Delay between each detection (in seconds)

-- FINDING THE PLAYER DETECTOR AUTOMATICALLY --
local detector = nil
for _, name in ipairs(peripheral.getNames()) do
    if peripheral.getType(name) == "player_detector" then
        detector = peripheral.wrap(name)
        break
    end
end

if not detector then
    print("No player detector found!")
    return
end

print("Player detector found on " .. peripheral.getName(detector))
print("Monitoring players in range " .. detectionRange .. "...")

-- STATE TRACKING --
local redstoneState = false

-- FUNCTION TO SET REDSTONE CLEANLY --
local function setRedstone(state)
    if redstoneState ~= state then
        redstone.setOutput(redstoneSide, state)
        redstoneState = state
        print("Redstone " .. (state and "ON" or "OFF"))
    end
end

-- MAIN LOOP --
while true do
    local players = detector.getPlayersInRange(detectionRange)
    local detected = #players > 0

    if detected then
        setRedstone(true)
    else
        setRedstone(false)
    end

    sleep(checkDelay)
end