jille_Jr icon

CC: Monitor test

jille_Jr | PRO | 05/28/14 01:34:29 PM UTC | 0 ⭐ | 480 👁️ | Never ⏰ | []
Lua |

1.14 KB

|

None

|

0 👍

/

0 👎

 
local xPos,yPos = 15,6
local mouseX,mouseY = 15,2
local monitor = peripheral.wrap("top")
or error("Unable to wrap monitor!",0)
 
local function closest(x,y)
    local nearX,nearY = x,y
    local nearestDistance = math.huge
 
    for xOffset = -1,1 do
        for yOffset = -1,1 do
            if (xOffset==0 or yOffset==0) and yOffset~=xOffset then
                local dx = x+xOffset-xPos
                local dy = y+yOffset-yPos
                local distance = math.sqrt(dx^2+dy^2)
 
                if distance < nearestDistance then
                    nearX = x + xOffset
                    nearY = y + yOffset
                end
            end
        end
    end
 
    return nearX,nearY
end
 
local function draw()
    monitor.clear()
 
    monitor.setCursorPos(mouseX,mouseY)
    monitor.write("X")
 
    monitor.setCursorPos(closest(mouseX,mouseY))
    monitor.write("o")
 
    monitor.setCursorPos(xPos,yPos)
    monitor.write("T")
end
 
local updateRate = 1/5
local update = os.startTimer(updateRate)
while true do
    local ev,p1,p2,p3,p4,p5 = os.pullEvent()
 
    if ev == "timer" and p1 == update then
        -- time to draw
        update = os.startTimer(updateRate)
        draw()
    elseif ev == "monitor_touch" then
        -- p1 = side of monitor
        mouseX = p2
        mouseY = p3
    end
end

Comments