mrWhiskasss

Секундомер - таймер

Oct 24th, 2021 (edited)
747
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local component = require "component"
  2. local event = require "event"
  3. local term = require "term"
  4. local computer = require "computer"
  5. local gpu = component.gpu
  6.  
  7. local key_space = require("keyboard").keys.space
  8. local running = true
  9. local x, y, width, height
  10. local outputWidth = 12 -- 00000:00.000 == 9 chars
  11. local startTime, timerEvent
  12.  
  13. local events = setmetatable({}, {__index = function() return function() end end})
  14. function events.key_up(keyboard, char, code, player)
  15.   if (code == key_space) then
  16.     running = false
  17.   end  
  18. end
  19.  
  20. function events.screen_resized(screenAddress, newWidth, newHeight)
  21.   width, height = newWidth, newHeight
  22.   x = math.max(1, math.floor((width - outputWidth) / 2))
  23.   y = math.max(1, math.floor(height / 2))
  24.  
  25.   term.clear()
  26.   clockTimer(true)
  27. end
  28.  
  29. function events.touch(adr, x, y, button, player)
  30.   if (timerEvent) then
  31.     event.cancel(timerEvent)
  32.     timerEvent = nil
  33.   else
  34.     startTime = computer.uptime()
  35.     timerEvent = event.timer(1/20, clockTimer, math.huge)
  36.   end
  37. end
  38.  
  39. function clockTimer(reset)
  40.   if (reset) then
  41.     gpu.set(x, y, "00:00.000")
  42.   else
  43.     local m, s, ms
  44.     local t = math.floor((computer.uptime() - startTime) * 1000)
  45.     ms = t % 1000
  46.     t = math.floor(t / 1000)
  47.     s = t % 60
  48.     t = math.floor(t / 60)
  49.     m = t % 60
  50.     gpu.set(x, y, string.format("%05d:%02d.%03d", m, s, ms))
  51.   end
  52. end
  53.  
  54. function handleEvent(event, ...)
  55.   if (event) then
  56.     events[event](...)
  57.   end  
  58. end
  59.  
  60. local prevWidth, prevHeight = gpu.getResolution()
  61. if (not gpu.setResolution(outputWidth, 1)) then
  62.   events.screen_resized(false, prevWidth, prevHeight)
  63. end
  64.  
  65. while running do
  66.   handleEvent(event.pull())
  67. end
  68.  
  69. if (timerEvent) then event.cancel(timerEvent) end
  70. gpu.setResolution(prevWidth, prevHeight)
RAW Paste Data