Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local FILE = "/usr/share/db"
- local BACKUP = "/usr/share/dbback"
- local PORT = 666
- ---===---
- local com = require("component")
- local fs = require("filesystem")
- local term = require("term")
- local unicode = require("unicode")
- local event = require("event")
- local ser = require("serialization")
- local gpu = com.gpu
- local modem = com.modem
- local w,h = gpu.getResolution()
- ---===---
- modem.open(PORT)
- local items = {}
- if not fs.exists(FILE) then
- local temp = io.open(FILE, "w")
- temp:write("recipes = {}\n")
- temp:close()
- end
- local function hint(part)
- part = (part or "")
- local contains = {}
- for i = 1, #items, 1 do
- if unicode.sub(items[i], 1, #part) == part then
- table.insert(contains, items[i])
- end
- end
- if #contains == 0 then
- return {part}
- end
- return contains
- end
- local function updateList(noDB)
- if not noDB then
- dofile(FILE)
- end
- items = {}
- for i, _ in pairs(recipes) do
- table.insert(items, i)
- end
- end
- local function centerY(text, line)
- local textDiv = math.floor(unicode.len(text) / 2)
- local widthDiv = math.floor(w / 2)
- gpu.set(widthDiv - textDiv - 1, line, text)
- end
- local function saveAll()
- print("Создание резервной копии...")
- fs.remove(BACKUP)
- fs.copy(FILE, BACKUP)
- print("Сохранение...")
- local temp = io.open(FILE, "w")
- temp:write("recipes = {}\n\n")
- for name, item in pairs(recipes) do
- temp:write("recipes[\"" .. name .. "\"] = {\n")
- temp:write(" [\"fingerprint\"] = {\n")
- temp:write(" [\"id\"] = \"" .. item.fingerprint.id .. "\",\n")
- temp:write(" [\"dmg\"] = " .. item.fingerprint.dmg .. "\n")
- temp:write(" },\n")
- if item.recipe then
- temp:write(" [\"qty\"] = " .. item.qty .. ",\n")
- temp:write(" [\"recipe\"] = {\n")
- temp:write(" \"" .. item.recipe[1] .. "\", \"" .. item.recipe[2] .. "\", \"" .. item.recipe[3] .. "\",\n")
- temp:write(" \"" .. item.recipe[4] .. "\", \"" .. item.recipe[5] .. "\", \"" .. item.recipe[6] .. "\",\n")
- temp:write(" \"" .. item.recipe[7] .. "\", \"" .. item.recipe[8] .. "\", \"" .. item.recipe[9] .. "\"\n")
- temp:write(" }\n")
- temp:write("}\n\n")
- else
- temp:write(" [\"qty\"] = " .. item.qty .. "\n")
- temp:write("}\n\n")
- end
- end
- temp:close()
- print("Завершено!")
- os.sleep(1)
- end
- local function addRecipe(edit)
- term.clear()
- gpu.set(1, 1, string.rep("-", w))
- if not edit then
- centerY("ДОБАВЛЕНИЕ РЕЦЕПТА", 1)
- else
- centerY("ИЗМЕНЕНИЕ РЕЦЕПТА", 1)
- end
- term.setCursor(1, 2)
- io.write("Название рецепта: ")
- if edit then funcHint = hint end
- local name = unicode.sub(term.read(nil, nil, funcHint), 1, -2)
- local oldName, newName
- if recipes[name] ~= nil and not edit then
- print("Данное имя уже существует!")
- os.sleep(1)
- return
- elseif edit and recipes[name] == nil then
- print("Данного рецепта не существует!")
- os.sleep(1)
- return
- elseif recipes[name] ~= nil and edit then
- print("Найден рецепт \"" .. name .. "\":")
- print(" ID: " .. recipes[name].fingerprint.id)
- print(" Meta: " .. recipes[name].fingerprint.dmg)
- print(" Количество: " .. recipes[name].qty)
- if recipes[name].recipe ~= nil then
- print(" Рецепт:")
- for i = 1, 9, 1 do
- print(" [" .. i .. "] " .. recipes[name].recipe[i])
- end
- end
- io.write("\nНажмите [Enter] для изменения...")
- local keyData = {event.pull("key_down")}
- if keyData[1] == nil or keyData[3] ~= 13 then
- return
- end
- io.write("\nНовое имя (оставьте пустым для старого): ")
- newName = unicode.sub(term.read(), 1, -2)
- end
- io.write("ID: ")
- local id = unicode.sub(term.read(), 1, -2)
- io.write("Meta: ")
- local dmg = unicode.sub(term.read(), 1, -2)
- print("Нажмите [Enter], если хотите задать рецепт, и любую другую клавишу в противном случае")
- local makeRecipe = true
- local keyData = {event.pull("key_down")}
- if keyData[1] == nil or keyData[3] ~= 13 then
- makeRecipe = false
- end
- local qty = 1
- local recipe = {}
- local history = {}
- if makeRecipe then
- repeat
- term.clearLine()
- local _, y = term.getCursor()
- term.setCursor(1, y)
- io.write("Выходное количество: ")
- qty = unicode.sub(term.read(nil, false), 1, -2)
- until tonumber(qty) ~= nil and tonumber(qty) > 0
- print("")
- print("Этап создания рецепта")
- local item = ""
- for i = 1, 9, 1 do
- item = ""
- print("Слот #" .. i)
- print("(оставьте пустым для пропуска):")
- io.write(": ")
- item = term.read(history, nil, hint)
- table.insert(recipe, unicode.sub(item, 1, -2))
- print("Записано: " .. recipe[i] .. "\n")
- end
- end
- io.write("[ДАЛЕЕ ->]")
- repeat
- local keyData = {event.pull("key_down")}
- until keyData[1] ~= nil and keyData[3] == 13
- term.clear()
- term.setCursor(1, 2)
- gpu.set(1, 1, string.rep("-", w))
- centerY("ПРИМЕНЕНИЕ ИЗМЕНЕНИЙ", 1)
- if not edit then
- print("Вы запросили добавить следующий рецепт:")
- else
- print("Вы запросили изменить рецепт так:")
- end
- if edit and newName ~= "" then
- oldName = name
- name = newName
- end
- print(" Имя: " .. name)
- print(" ID: " .. id)
- print(" Meta: " .. dmg)
- print(" Количество: " .. qty)
- if recipe[1] ~= nil then
- print(" Рецепт:")
- for i = 1, 9, 1 do
- print(" [" .. i .. "] " .. recipe[i])
- end
- end
- io.write("\nПрименить изменения? [y/N] ")
- local r = unicode.sub(term.read(), 1, -2)
- if r == "y" or r == "Y" or r == "yes" or r == "YES" then
- if edit and newName ~= "" then
- recipes[oldName] = nil
- end
- if recipe[1] then
- recipes[name] = {
- ["fingerprint"] = {
- ["id"] = id,
- ["dmg"] = dmg
- },
- ["qty"] = qty,
- ["recipe"] = recipe
- }
- else
- recipes[name] = {
- ["fingerprint"] = {
- ["id"] = id,
- ["dmg"] = dmg
- },
- ["qty"] = qty
- }
- end
- print("Изменения применены. Не забудьте сохранить базу данных рецептов!")
- else
- print("Изменения утеряны")
- end
- os.sleep(1)
- end
- local function delRecipe()
- updateList(true)
- term.clear()
- term.setCursor(1, 2)
- gpu.set(1, 1, string.rep("-", w))
- centerY("УДАЛЕНИЕ РЕЦЕПТА", 1)
- io.write("Введите имя рецепта для удаления: ")
- local item = unicode.sub(term.read(nil, nil, hint), 1, -2)
- if recipes[item] then
- print("Найден рецепт \"" .. item .. "\":")
- print(" ID: " .. recipes[item].fingerprint.id)
- print(" Meta: " .. recipes[item].fingerprint.dmg)
- print(" Количество: " .. recipes[item].qty)
- if recipes[item].recipe ~= nil then
- print(" Рецепт:")
- for i = 1, 9, 1 do
- print(" [" .. i .. "] " .. recipes[item].recipe[i])
- end
- end
- io.write("\nВы уверены, что хотите удалить данный рецепт? [y/N] ")
- local r = unicode.sub(term.read(), 1, -2)
- if r == "y" or r == "Y" or r == "yes" or r == "YES" then
- recipes[item] = nil
- print("Рецепт был удалён. Сохраните изменения для применения.")
- else
- print("Нет изменений.")
- end
- else
- print("Данный рецепт не найден!")
- end
- os.sleep(1)
- end
- local function showRecipe()
- term.clear()
- term.setCursor(1, 2)
- gpu.set(1, 1, string.rep("-", w))
- centerY("ПРОСМОТР РЕЦЕПТА", 1)
- io.write("Имя рецепта: ")
- local name = unicode.sub(term.read(nil, nil, hint), 1, -2)
- if recipes[name] then
- print("Найден рецепт \"" .. name .. "\":")
- print(" ID: " .. recipes[name].fingerprint.id)
- print(" Meta: " .. recipes[name].fingerprint.dmg)
- print(" Количество: " .. recipes[name].qty)
- if recipes[name].recipe then
- print(" Рецепт:")
- for i = 1, 9, 1 do
- print(" [" .. i .. "] " .. recipes[name].recipe[i])
- end
- end
- print("\nНажмите [Enter] для возврата...")
- local keyData
- repeat
- keyData = {event.pull("key_down")}
- until keyData[1] ~= nil and keyData[3] == 13
- else
- print("Этот рецепт не существует!")
- os.sleep(1)
- end
- end
- local function scanRecipe()
- term.clear()
- term.setCursor(1, 2)
- gpu.set(1, 1, string.rep("-", w))
- centerY("СКАНИРОВАНИЕ РЕЦЕПТА", 1)
- print("Включено прослушивание эфира. Ожидание сообщения от робота...")
- print("Нажмите [Enter] для возвращения")
- local recipe = {}
- repeat
- recipe = {event.pull(30)}
- until recipe[1] ~= nil and (recipe[1] == "key_down" or recipe[1] == "modem_message")
- if recipe[1] == "key_down" then
- return
- end
- recipe = recipe[6]
- recipe = ser.unserialize(recipe)
- local name = ""
- repeat
- term.clearLine()
- local _, y = term.getCursor()
- term.setCursor(1, y)
- io.write("Введите имя рецепта: ")
- name = unicode.sub(term.read(nil, false), 1, -2)
- until not recipes[name]
- print("")
- local id = recipe[10].name
- local meta = recipe[10].damage
- local qty, rcp = 1, {}
- local makeRcp = false
- for i =1, 9, 1 do
- if recipe[i] ~= "" then
- makeRcp = true
- break
- end
- end
- if makeRcp then
- repeat
- term.clearLine()
- local _, y = term.getCursor()
- term.setCursor(1, y)
- io.write("Выходное количество: ")
- qty = unicode.sub(term.read(nil, false), 1, -2)
- until tonumber(qty) and tonumber(qty) > 0
- print("")
- qty = tonumber(qty)
- for i = 1, 9, 1 do
- if recipe[i] ~= "" and recipe[i] ~= nil then
- for rcpName, stack in pairs(recipes) do
- -- print(rcpName, stack.fingerprint.id, stack.fingerprint.dmg, recipe[i].name, recipe[i].damage)
- if recipe[i].name == stack.fingerprint.id and recipe[i].damage == stack.fingerprint.dmg then
- rcp[i] = rcpName
- end
- end
- if rcp[i] == nil then
- io.stderr:write("Не найден компонент: " .. recipe[i].name .. "@" .. recipe[i].damage)
- os.sleep(1)
- return
- end
- else
- rcp[i] = ""
- end
- end
- end
- term.clear()
- term.setCursor(1, 2)
- gpu.set(1, 1, string.rep("-", w))
- centerY("ПРИМЕНЕНИЕ ИЗМЕНЕНИЙ", 1)
- print("Вы запросили добавить следующий рецепт:")
- print(" Имя: " .. name)
- print(" ID: " .. id)
- print(" Meta: " .. meta)
- print(" Количество: " .. qty)
- if rcp[1] then
- print(" Рецепт:")
- for i =1, 9, 1 do
- print(" [" .. i .. "] " .. rcp[i])
- end
- end
- io.write("Применить изменения? [y/N] ")
- local apply = unicode.sub(term.read(), 1, -2)
- if apply == "y" or apply == "Y" or apply == "yes" or apply == "Yes" or apply == "YES" then
- if rcp[1] then
- recipes[name] = {
- ["fingerprint"] = {
- ["id"] = id,
- ["dmg"] = meta
- },
- ["qty"] = qty,
- ["recipe"] = {
- rcp[1], rcp[2], rcp[3],
- rcp[4], rcp[5], rcp[6],
- rcp[7], rcp[8], rcp[9]
- }
- }
- else
- recipes[name] = {
- ["fingerprint"] = {
- ["id"] = id,
- ["dmg"] = meta
- },
- ["qty"] = qty
- }
- end
- print("Изменения применены. Не забудьте сохранить базу данных!")
- else
- print("Изменения утеряны.")
- end
- os.sleep(1)
- end
- updateList()
- ::main::
- while true do
- local mode = nil
- repeat
- term.clear()
- term.setCursor(1, 1)
- print("БД: " .. FILE)
- print(" [0] Выход")
- print(" [1] Добавление рецепта")
- print(" [2] Удаление рецепта")
- print(" [3] Изменение рецепта")
- print(" [4] Сохранение изменений")
- print(" [5] Обновить список")
- print(" [6] Показать информацию о рецепте")
- print(" [7] Сканирование рецепта")
- io.write("Выберите действие: ")
- mode = term.read()
- until tonumber(mode) ~= nil and tonumber(mode) < 8 and tonumber(mode) > -1
- mode = tonumber(mode)
- if mode == 0 then
- term.clear()
- term.setCursor(1, 1)
- os.exit()
- elseif mode == 1 then
- addRecipe()
- elseif mode == 2 then
- delRecipe()
- elseif mode == 3 then
- addRecipe(true)
- elseif mode == 4 then
- saveAll()
- elseif mode == 5 then
- updateList()
- elseif mode == 6 then
- showRecipe()
- elseif mode == 7 then
- scanRecipe()
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement