oaky / sugarcane public computer
0
0
Web IDE
main
5 commits
oaky Update sugarcane
fb430669 2026-09-25
main
Update sugarcane2026-09-25
Overview
MIT

Sugarcane

Quick Install on your ComputerCraft device

Type this command in the terminal:

hub get sugarcane
📖
No README.md in this repository

Documenting your script or package helps other players learn how to install, configure and run it.

startup.lua main
--[[
=========================================================================
  Zuckerrohr-Farm-Zaehler - eigenstaendiges Statistik-Display
=========================================================================
  Unabhaengig vom Lagersystem. Zaehlt, wie viel Zuckerrohr INSGESAMT
  geerntet wurde - auch wenn es danach automatisch weiterverarbeitet wird
  (z.B. per Hopper in einen Crafter).

  WICHTIG - Verkabelung:
    Ein normaler Hopper zieht alle 0,4s aus einer Kiste. Wuerde dieses
    Script (Poll alle paar Sekunden) versuchen, aus DERSELBEN Kiste zu
    zaehlen, aus der GLEICHZEITIG ein Hopper weiterzieht, koennte
    Zuckerrohr nachwachsen UND vom Hopper schon weitergeschoben sein,
    BEVOR das Script je hinschaut - der Zuwachs waere komplett unsichtbar.

    Deshalb zaehlt das Script NICHT an der Kiste, aus der der
    Crafter-Hopper zieht, sondern an einer EIGENEN Zwischen-Kiste davor:

      Farm -> [SOURCE_CHEST]  <- NUR der Farm-Hopper liefert hier rein,
                                   NICHTS anderes zieht hier raus
                |
                | (das Script selbst, nicht per Hopper!)
                v
           [FORWARD_CHEST]    <- hier zieht der bestehende Hopper zum
                                   Crafter weiter wie bisher

    Das Script ist damit der EINZIGE, der aus SOURCE_CHEST entnimmt -
    kein Wettrennen mehr moeglich. Bei jedem Poll zaehlt es ALLES, was
    dort liegt, und schiebt es selbst sofort nach FORWARD_CHEST weiter.

  Keine Interaktion, keine Touch-Events - reine Anzeige.

  Starten mit: sugarcane
=========================================================================
]]

------------------------------------------------------------------------
-- Einstellungen - anpassen!
------------------------------------------------------------------------

local SOURCE_CHEST   = "minecraft:chest_108"  -- NUR vom Farm-Hopper befuellt
local FORWARD_CHEST  = "minecraft:chest_109"  -- hier zieht der Crafter-Hopper wie bisher
local MONITOR         = "left"
local ITEM_NAME       = "minecraft:sugar_cane"
local POLL_INTERVAL   = 2      -- Sekunden zwischen zwei Scans
local STATE_FILE      = "sugarcane_stats.txt"

-- Fuer "letzte Stunde"/"letzte 24h" wird der Gesamtzaehler periodisch als
-- Zeitpunkt+Wert mitgeschrieben (History). RECORD_INTERVAL bestimmt den
-- Abstand zwischen zwei Aufzeichnungen, HISTORY_RETENTION wie lange sie
-- aufbewahrt werden (etwas mehr als 24h als Sicherheitspuffer).
local RECORD_INTERVAL   = 60            -- Sekunden zwischen History-Punkten
local HISTORY_RETENTION = 25 * 3600     -- Sekunden (25h)

------------------------------------------------------------------------
-- Persistenz
------------------------------------------------------------------------

local function loadState()
  local state
  if fs.exists(STATE_FILE) then
    local f = fs.open(STATE_FILE, "r")
    if f then
      local data = f.readAll()
      f.close()
      local ok, t = pcall(textutils.unserialize, data)
      if ok and type(t) == "table" and t.total then state = t end
    end
  end

  local now = os.epoch("utc")
  state = state or { total = 0 }
  -- Abwaertskompatibel: alte Dateien kannten nur "sessionStart" - als
  -- Ersatz fuer den All-Time-Start verwenden, statt bei 0 neu anzufangen.
  state.firstStart = state.firstStart or state.sessionStart or now
  state.history = state.history or {}
  state.lastRecordT = state.lastRecordT or 0
  return state
end

local function saveState(state)
  local f = fs.open(STATE_FILE, "w")
  if not f then return end
  f.write(textutils.serialize(state))
  f.close()
end

------------------------------------------------------------------------
-- Zaehl-Logik (pure Funktion, ohne Peripheral-Zugriff - testbar)
------------------------------------------------------------------------

-- Summiert alle Zuckerrohr-Slots in 'list' und gibt zurueck, was
-- weitergeleitet werden muss: Gesamtmenge + Liste { {slot, count}, ... }.
-- 'list' ist das rohe list()-Ergebnis der Zaehl-Kiste.
local function collectItems(list, itemName)
  local total = 0
  local toForward = {}
  for slot, item in pairs(list) do
    if item.name == itemName then
      total = total + item.count
      toForward[#toForward + 1] = { slot = slot, count = item.count }
    end
  end
  return total, toForward
end

------------------------------------------------------------------------
-- History-Logik (pure Funktionen, ohne Peripheral-/Zeit-Zugriff - testbar)
------------------------------------------------------------------------

-- Entfernt Eintraege, die aelter als 'retentionMs' sind.
local function pruneHistory(history, nowMs, retentionMs)
  local out = {}
  for _, e in ipairs(history) do
    if nowMs - e.t <= retentionMs then out[#out + 1] = e end
  end
  return out
end

-- Juengster Eintrag mit Zeitpunkt <= targetMs, oder nil wenn die History
-- nicht so weit zurueckreicht.
local function totalAtOrBefore(history, targetMs)
  local result = nil
  for _, e in ipairs(history) do
    if e.t <= targetMs and (not result or e.t > result.t) then result = e end
  end
  return result
end

-- Wieviel wurde in den letzten 'windowMs' Millisekunden geerntet?
-- Reicht die History nicht so weit zurueck (Script laeuft noch nicht
-- lange genug), wird konservativ ab dem aeltesten bekannten Punkt
-- gerechnet ("alles seit Start") statt einen falschen Wert zu raten.
-- Ganz ohne History (noch kein einziger Punkt aufgezeichnet) -> 0.
local function windowedGain(history, currentTotal, nowMs, windowMs)
  if #history == 0 then return 0 end
  local target = nowMs - windowMs
  local entry = totalAtOrBefore(history, target) or history[1]
  return currentTotal - entry.total
end

------------------------------------------------------------------------
-- Anzeige
------------------------------------------------------------------------

local function centerText(monitor, y, text, color)
  local w = select(1, monitor.getSize())
  monitor.setTextColor(color)
  monitor.setCursorPos(math.max(1, math.floor((w - #text) / 2) + 1), y)
  monitor.write(text)
end

local function render(monitor, state)
  monitor.setBackgroundColor(colors.black)
  monitor.clear()

  local now = os.epoch("utc")

  centerText(monitor, 2, "ZUCKERROHR-FARM", colors.lime)

  centerText(monitor, 4, "Insgesamt geerntet:", colors.gray)
  centerText(monitor, 5, tostring(state.total), colors.white)

  local elapsedMin = math.max((now - state.firstStart) / 60000, 1 / 60)
  local overallRate = state.total / elapsedMin
  centerText(monitor, 7, ("Ø gesamt: %.1f/min"):format(overallRate), colors.yellow)

  local recentGain = windowedGain(state.history, state.total, now, 5 * 60 * 1000)
  centerText(monitor, 8, ("Aktuell (5 Min): %.1f/min"):format(recentGain / 5), colors.orange)

  local lastHour = windowedGain(state.history, state.total, now, 3600 * 1000)
  centerText(monitor, 10, ("Letzte Stunde: %d"):format(lastHour), colors.white)

  local last24h = windowedGain(state.history, state.total, now, 24 * 3600 * 1000)
  centerText(monitor, 11, ("Letzte 24 Std: %d"):format(last24h), colors.white)
end

------------------------------------------------------------------------
-- Hauptschleife
------------------------------------------------------------------------

local function main()
  local monitor = peripheral.wrap(MONITOR)
  if not monitor then
    error("Monitor '" .. MONITOR .. "' nicht gefunden! MONITOR oben anpassen.")
  end
  pcall(monitor.setTextScale, 1)

  local state = loadState()

  while true do
    local src = peripheral.wrap(SOURCE_CHEST)
    if not src then
      print("[!] Zaehl-Kiste '" .. SOURCE_CHEST .. "' nicht gefunden.")
    elseif not peripheral.isPresent(FORWARD_CHEST) then
      print("[!] Ziel-Kiste '" .. FORWARD_CHEST .. "' nicht gefunden.")
    else
      local ok, list = pcall(src.list)
      if ok and list and next(list) ~= nil then
        local gained, toForward = collectItems(list, ITEM_NAME)
        for _, mv in ipairs(toForward) do
          src.pushItems(FORWARD_CHEST, mv.slot, mv.count)
        end
        if gained > 0 then
          state.total = state.total + gained
          saveState(state)  -- Zuwachs sofort persistieren, nicht erst beim naechsten History-Punkt
        end
      end

      -- Periodisch zusaetzlich einen History-Punkt aufzeichnen (auch wenn
      -- sich gerade nichts geaendert hat), damit "letzte Stunde"/"letzte
      -- 24h" auch ueber laengere Ruhephasen hinweg korrekt bleiben.
      local nowMs = os.epoch("utc")
      if nowMs - state.lastRecordT >= RECORD_INTERVAL * 1000 then
        table.insert(state.history, { t = nowMs, total = state.total })
        state.history = pruneHistory(state.history, nowMs, HISTORY_RETENTION * 1000)
        state.lastRecordT = nowMs
        saveState(state)
      end
    end

    render(monitor, state)
    sleep(POLL_INTERVAL)
  end
end

main()

Usage

Once installed with hub get sugarcane, run:

sugarcane
Careful what you run: This script was written by oaky, not by us. It runs with full access to the computer you install it on — it can read and delete files there. Read it before you run it.

About

No description provided.

MIT License
★ 0 stars
0 in-game downloads

Hardware Targets

computer

Owner