Minecraft Lua计时器脚本暂停恢复后时间跳变问题求助
Lua Minecraft计时器问题修复
核心故障原因
- 重复定义
keyboard函数:后定义的启停逻辑函数覆盖了重置逻辑函数,导致重置键完全失效。 - 暂停恢复逻辑错误:从暂停状态切回计时状态时,未调整初始计时时间
startTime,仍使用首次启动的时间戳计算总时长,暂停期间的时长被算入计时结果,因此出现时间跳变。 - 时间换算逻辑bug:
timeText函数计算小时时错误扣减一天的秒数(86400),而非一小时的秒数(3600),会导致小时统计完全错误。 - 变量逻辑冗余:
previoustime变量未正确存储累计计时时长,恢复计时时给局部变量time赋值无实际作用,未对接全局计时逻辑。
修复后完整代码
name = "Stopwatch" description = "Count time for whatever reason..." positionX = 0 positionY = 0 sizeX = 24 sizeY = 10 scale = 1 START_STOP_KEY = 0x55 -- 对应按键U RESET_KEY = 0x4A -- 对应按键J --[[ Stopwatch Module Script 如需修改按键可查询Windows虚拟键码表获取对应编码 ]]-- -------------script-code------------- state = 0 startTime = 0 stopTime = 0 -- 合并两个重复的keyboard函数,避免逻辑覆盖 function keyboard(key, isDown) if (isDown == true) then -- 重置逻辑 if (key == RESET_KEY) then state = 0 startTime = 0 stopTime = 0 -- 启停逻辑 elseif (key == START_STOP_KEY) then if (state == 0) then -- 首次启动 state = 1 startTime = os.time() elseif (state == 1) then -- 暂停 state = 2 stopTime = os.time() elseif (state == 2) then -- 恢复计时,调整startTime抵消暂停时长 state = 1 startTime = os.time() - (stopTime - startTime) end end end end TimerText = "00:00" TextColor = {r=30,g=255,b=30,a=255} function doubleDigit(number) if (number < 10) then return "0" .. math.floor(number) else return math.floor(number) end end function timeText(time) local result = "" local days = 0 while (time > 86399) do days = days + 1 time = time - 86400 end local hours = 0 -- 修复小时计算错误,扣减3600秒而非86400秒 while (time > 3599) do hours = hours + 1 time = time - 3600 end local minutes = 0 while (time > 59) do minutes = minutes + 1 time = time - 60 end if (days == 0) then if (hours == 0) then return doubleDigit(minutes) .. ":" .. doubleDigit(time) else return math.floor(hours) .. " : " .. doubleDigit(minutes) .. ":" ..doubleDigit(time) end else return math.floor(days) .. " : " .. doubleDigit(hours) .. " : " .. doubleDigit(minutes) .. ":" .. doubleDigit(time) end end function update() if (state == 0) then TextColor = {r=30,g=255,b=30,a=255} TimerText = "00:00" elseif (state == 1) then TimerText = timeText(os.time() - startTime) TextColor = {r=30,g=255,b=30,a=255} elseif (state == 2) then TimerText = timeText(stopTime - startTime) TextColor = {r=30,g=30,b=255,a=255} end end function render() local font = gui.font() local tw = font.width(TimerText) gfx.color(0,0,0,120) gfx.rect(0, 0, tw + 4, 10) gfx.color(TextColor.r, TextColor.g, TextColor.b, TextColor.a) gfx.text(2, 1, TimerText) end
内容的提问来源于stack exchange,提问作者SebyGHG
相关产品推荐
相关产品推荐

