Advertisement
fingercomp

[OC] Автокрафт: comp/RECIPES.LUA

Aug 15th, 2015
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local FILE = "/usr/share/db"
  2. local BACKUP = "/usr/share/dbback"
  3. local PORT = 666
  4. ---===---
  5. local com = require("component")
  6. local fs = require("filesystem")
  7. local term = require("term")
  8. local unicode = require("unicode")
  9. local event = require("event")
  10. local ser = require("serialization")
  11. local gpu = com.gpu
  12. local modem = com.modem
  13. local w,h = gpu.getResolution()
  14. ---===---
  15. modem.open(PORT)
  16. local items = {}
  17. if not fs.exists(FILE) then
  18.   local temp = io.open(FILE, "w")
  19.   temp:write("recipes = {}\n")
  20.   temp:close()
  21. end
  22.  
  23. local function hint(part)
  24.   part = (part or "")
  25.   local contains = {}
  26.   for i = 1, #items, 1 do
  27.     if unicode.sub(items[i], 1, #part) == part then
  28.       table.insert(contains, items[i])
  29.     end
  30.   end
  31.   if #contains == 0 then
  32.     return {part}
  33.   end
  34.   return contains
  35. end
  36.  
  37. local function updateList(noDB)
  38.   if not noDB then
  39.     dofile(FILE)
  40.   end
  41.  
  42.   items = {}
  43.   for i, _ in pairs(recipes) do
  44.     table.insert(items, i)
  45.   end
  46. end
  47.  
  48. local function centerY(text, line)
  49.   local textDiv = math.floor(unicode.len(text) / 2)
  50.   local widthDiv = math.floor(w / 2)
  51.   gpu.set(widthDiv - textDiv - 1, line, text)
  52. end
  53.  
  54. local function saveAll()
  55.   print("Создание резервной копии...")
  56.   fs.remove(BACKUP)
  57.   fs.copy(FILE, BACKUP)
  58.   print("Сохранение...")
  59.   local temp = io.open(FILE, "w")
  60.   temp:write("recipes = {}\n\n")
  61.   for name, item in pairs(recipes) do
  62.     temp:write("recipes[\"" .. name .. "\"] = {\n")
  63.     temp:write("  [\"fingerprint\"] = {\n")
  64.     temp:write("    [\"id\"] = \"" .. item.fingerprint.id .. "\",\n")
  65.     temp:write("    [\"dmg\"] = " .. item.fingerprint.dmg .. "\n")
  66.     temp:write("  },\n")
  67.     if item.recipe then
  68.       temp:write("  [\"qty\"] = " .. item.qty .. ",\n")
  69.       temp:write("  [\"recipe\"] = {\n")
  70.       temp:write("    \"" .. item.recipe[1] .. "\", \"" .. item.recipe[2] .. "\", \"" .. item.recipe[3] .. "\",\n")
  71.       temp:write("    \"" .. item.recipe[4] .. "\", \"" .. item.recipe[5] .. "\", \"" .. item.recipe[6] .. "\",\n")
  72.       temp:write("    \"" .. item.recipe[7] .. "\", \"" .. item.recipe[8] .. "\", \"" .. item.recipe[9] .. "\"\n")
  73.       temp:write("  }\n")
  74.       temp:write("}\n\n")
  75.     else
  76.       temp:write("  [\"qty\"] = " .. item.qty .. "\n")
  77.       temp:write("}\n\n")
  78.     end
  79.   end
  80.   temp:close()
  81.   print("Завершено!")
  82.   os.sleep(1)
  83. end
  84.  
  85. local function addRecipe(edit)
  86.   term.clear()
  87.   gpu.set(1, 1, string.rep("-", w))
  88.   if not edit then
  89.     centerY("ДОБАВЛЕНИЕ РЕЦЕПТА", 1)
  90.   else
  91.     centerY("ИЗМЕНЕНИЕ РЕЦЕПТА", 1)
  92.   end
  93.   term.setCursor(1, 2)
  94.   io.write("Название рецепта: ")
  95.   if edit then funcHint = hint end
  96.   local name = unicode.sub(term.read(nil, nil, funcHint), 1, -2)
  97.   local oldName, newName
  98.   if recipes[name] ~= nil and not edit then
  99.     print("Данное имя уже существует!")
  100.     os.sleep(1)
  101.     return
  102.   elseif edit and recipes[name] == nil then
  103.     print("Данного рецепта не существует!")
  104.     os.sleep(1)
  105.     return
  106.   elseif recipes[name] ~= nil and edit then
  107.     print("Найден рецепт \"" .. name .. "\":")
  108.     print(" ID: " .. recipes[name].fingerprint.id)
  109.     print(" Meta: " .. recipes[name].fingerprint.dmg)
  110.     print(" Количество: " .. recipes[name].qty)
  111.     if recipes[name].recipe ~= nil then
  112.       print(" Рецепт:")
  113.       for i = 1, 9, 1 do
  114.         print("  [" .. i .. "] " .. recipes[name].recipe[i])
  115.       end
  116.     end
  117.     io.write("\nНажмите [Enter] для изменения...")
  118.     local keyData = {event.pull("key_down")}
  119.     if keyData[1] == nil or keyData[3] ~= 13 then
  120.       return
  121.     end
  122.     io.write("\nНовое имя (оставьте пустым для старого): ")
  123.     newName = unicode.sub(term.read(), 1, -2)
  124.   end
  125.   io.write("ID: ")
  126.   local id = unicode.sub(term.read(), 1, -2)
  127.   io.write("Meta: ")
  128.   local dmg = unicode.sub(term.read(), 1, -2)
  129.   print("Нажмите [Enter], если хотите задать рецепт, и любую другую клавишу в противном случае")
  130.   local makeRecipe = true
  131.   local keyData = {event.pull("key_down")}
  132.   if keyData[1] == nil or keyData[3] ~= 13 then
  133.     makeRecipe = false
  134.   end
  135.   local qty = 1
  136.   local recipe = {}
  137.   local history = {}
  138.   if makeRecipe then
  139.     repeat
  140.       term.clearLine()
  141.       local _, y = term.getCursor()
  142.       term.setCursor(1, y)
  143.       io.write("Выходное количество: ")
  144.       qty = unicode.sub(term.read(nil, false), 1, -2)
  145.     until tonumber(qty) ~= nil and tonumber(qty) > 0
  146.     print("")
  147.     print("Этап создания рецепта")
  148.     local item = ""
  149.     for i = 1, 9, 1 do
  150.       item = ""
  151.       print("Слот #" .. i)
  152.       print("(оставьте пустым для пропуска):")
  153.       io.write(": ")
  154.       item = term.read(history, nil, hint)
  155.       table.insert(recipe, unicode.sub(item, 1, -2))
  156.       print("Записано: " .. recipe[i] .. "\n")
  157.     end
  158.   end
  159.   io.write("[ДАЛЕЕ ->]")
  160.   repeat
  161.     local keyData = {event.pull("key_down")}
  162.   until keyData[1] ~= nil and keyData[3] == 13
  163.  
  164.   term.clear()
  165.   term.setCursor(1, 2)
  166.   gpu.set(1, 1, string.rep("-", w))
  167.   centerY("ПРИМЕНЕНИЕ ИЗМЕНЕНИЙ", 1)
  168.   if not edit then
  169.     print("Вы запросили добавить следующий рецепт:")
  170.   else
  171.     print("Вы запросили изменить рецепт так:")
  172.   end
  173.   if edit and newName ~= "" then
  174.     oldName = name
  175.     name = newName
  176.   end
  177.   print(" Имя: " .. name)
  178.   print(" ID: " .. id)
  179.   print(" Meta: " .. dmg)
  180.   print(" Количество: " .. qty)
  181.   if recipe[1] ~= nil then
  182.     print(" Рецепт:")
  183.     for i = 1, 9, 1 do
  184.       print("  [" .. i .. "] " .. recipe[i])
  185.     end
  186.   end
  187.   io.write("\nПрименить изменения? [y/N] ")
  188.   local r = unicode.sub(term.read(), 1, -2)
  189.   if r == "y" or r == "Y" or r == "yes" or r == "YES" then
  190.     if edit and newName ~= "" then
  191.       recipes[oldName] = nil
  192.     end
  193.     if recipe[1] then
  194.       recipes[name] = {
  195.         ["fingerprint"] = {
  196.           ["id"] = id,
  197.           ["dmg"] = dmg
  198.         },
  199.         ["qty"] = qty,
  200.         ["recipe"] = recipe
  201.       }
  202.     else
  203.       recipes[name] = {
  204.         ["fingerprint"] = {
  205.           ["id"] = id,
  206.           ["dmg"] = dmg
  207.         },
  208.         ["qty"] = qty
  209.       }
  210.     end
  211.     print("Изменения применены. Не забудьте сохранить базу данных рецептов!")
  212.   else
  213.     print("Изменения утеряны")
  214.   end
  215.   os.sleep(1)
  216. end
  217.  
  218. local function delRecipe()
  219.   updateList(true)
  220.   term.clear()
  221.   term.setCursor(1, 2)
  222.   gpu.set(1, 1, string.rep("-", w))
  223.   centerY("УДАЛЕНИЕ РЕЦЕПТА", 1)
  224.   io.write("Введите имя рецепта для удаления: ")
  225.   local item = unicode.sub(term.read(nil, nil, hint), 1, -2)
  226.   if recipes[item] then
  227.     print("Найден рецепт \"" .. item .. "\":")
  228.     print(" ID: " .. recipes[item].fingerprint.id)
  229.     print(" Meta: " .. recipes[item].fingerprint.dmg)
  230.     print(" Количество: " .. recipes[item].qty)
  231.     if recipes[item].recipe ~= nil then
  232.       print(" Рецепт:")
  233.       for i = 1, 9, 1 do
  234.         print("  [" .. i .. "] " .. recipes[item].recipe[i])
  235.       end
  236.     end
  237.     io.write("\nВы уверены, что хотите удалить данный рецепт? [y/N] ")
  238.     local r = unicode.sub(term.read(), 1, -2)
  239.     if r == "y" or r == "Y" or r == "yes" or r == "YES" then
  240.       recipes[item] = nil
  241.       print("Рецепт был удалён. Сохраните изменения для применения.")
  242.     else
  243.       print("Нет изменений.")
  244.     end
  245.   else
  246.     print("Данный рецепт не найден!")
  247.   end
  248.   os.sleep(1)
  249. end
  250.  
  251. local function showRecipe()
  252.   term.clear()
  253.   term.setCursor(1, 2)
  254.   gpu.set(1, 1, string.rep("-", w))
  255.   centerY("ПРОСМОТР РЕЦЕПТА", 1)
  256.   io.write("Имя рецепта: ")
  257.   local name = unicode.sub(term.read(nil, nil, hint), 1, -2)
  258.   if recipes[name] then
  259.     print("Найден рецепт \"" .. name .. "\":")
  260.     print(" ID: " .. recipes[name].fingerprint.id)
  261.     print(" Meta: " .. recipes[name].fingerprint.dmg)
  262.     print(" Количество: " .. recipes[name].qty)
  263.     if recipes[name].recipe then
  264.       print(" Рецепт:")
  265.       for i = 1, 9, 1 do
  266.         print("  [" .. i .. "] " .. recipes[name].recipe[i])
  267.       end
  268.     end
  269.     print("\nНажмите [Enter] для возврата...")
  270.     local keyData
  271.     repeat
  272.       keyData = {event.pull("key_down")}
  273.     until keyData[1] ~= nil and keyData[3] == 13
  274.   else
  275.     print("Этот рецепт не существует!")
  276.     os.sleep(1)
  277.   end
  278. end
  279.  
  280. local function scanRecipe()
  281.   term.clear()
  282.   term.setCursor(1, 2)
  283.   gpu.set(1, 1, string.rep("-", w))
  284.   centerY("СКАНИРОВАНИЕ РЕЦЕПТА", 1)
  285.   print("Включено прослушивание эфира. Ожидание сообщения от робота...")
  286.   print("Нажмите [Enter] для возвращения")
  287.   local recipe = {}
  288.   repeat
  289.     recipe = {event.pull(30)}
  290.   until recipe[1] ~= nil and (recipe[1] == "key_down" or recipe[1] == "modem_message")
  291.   if recipe[1] == "key_down" then
  292.     return
  293.   end
  294.   recipe = recipe[6]
  295.   recipe = ser.unserialize(recipe)
  296.   local name = ""
  297.   repeat
  298.     term.clearLine()
  299.     local _, y = term.getCursor()
  300.     term.setCursor(1, y)
  301.     io.write("Введите имя рецепта: ")
  302.     name = unicode.sub(term.read(nil, false), 1, -2)
  303.   until not recipes[name]
  304.   print("")
  305.   local id = recipe[10].name
  306.   local meta = recipe[10].damage
  307.   local qty, rcp = 1, {}
  308.   local makeRcp = false
  309.   for i =1, 9, 1 do
  310.     if recipe[i] ~= "" then
  311.       makeRcp = true
  312.       break
  313.     end
  314.   end
  315.   if makeRcp then
  316.     repeat
  317.       term.clearLine()
  318.       local _, y = term.getCursor()
  319.       term.setCursor(1, y)
  320.       io.write("Выходное количество: ")
  321.       qty = unicode.sub(term.read(nil, false), 1, -2)
  322.     until tonumber(qty) and tonumber(qty) > 0
  323.     print("")
  324.     qty = tonumber(qty)
  325.     for i = 1, 9, 1 do
  326.       if recipe[i] ~= "" and recipe[i] ~= nil then
  327.         for rcpName, stack in pairs(recipes) do
  328. --        print(rcpName, stack.fingerprint.id, stack.fingerprint.dmg, recipe[i].name, recipe[i].damage)
  329.           if recipe[i].name == stack.fingerprint.id and recipe[i].damage == stack.fingerprint.dmg then
  330.             rcp[i] = rcpName
  331.           end
  332.         end
  333.         if rcp[i] == nil then
  334.           io.stderr:write("Не найден компонент: " .. recipe[i].name .. "@" .. recipe[i].damage)
  335.           os.sleep(1)
  336.           return
  337.         end
  338.       else
  339.         rcp[i] = ""
  340.       end
  341.     end
  342.   end
  343.   term.clear()
  344.   term.setCursor(1, 2)
  345.   gpu.set(1, 1, string.rep("-", w))
  346.   centerY("ПРИМЕНЕНИЕ ИЗМЕНЕНИЙ", 1)
  347.   print("Вы запросили добавить следующий рецепт:")
  348.   print(" Имя: " .. name)
  349.   print(" ID: " .. id)
  350.   print(" Meta: " .. meta)
  351.   print(" Количество: " .. qty)
  352.   if rcp[1] then
  353.     print(" Рецепт:")
  354.     for i =1, 9, 1 do
  355.       print("  [" .. i .. "] " .. rcp[i])
  356.     end
  357.   end
  358.   io.write("Применить изменения? [y/N] ")
  359.   local apply = unicode.sub(term.read(), 1, -2)
  360.   if apply == "y" or apply == "Y" or apply == "yes" or apply == "Yes" or apply == "YES" then
  361.     if rcp[1] then
  362.       recipes[name] = {
  363.         ["fingerprint"] = {
  364.           ["id"] = id,
  365.           ["dmg"] = meta
  366.         },
  367.         ["qty"] = qty,
  368.         ["recipe"] = {
  369.           rcp[1], rcp[2], rcp[3],
  370.           rcp[4], rcp[5], rcp[6],
  371.           rcp[7], rcp[8], rcp[9]
  372.         }
  373.       }
  374.     else
  375.       recipes[name] = {
  376.         ["fingerprint"] = {
  377.           ["id"] = id,
  378.           ["dmg"] = meta
  379.         },
  380.         ["qty"] = qty
  381.       }
  382.     end
  383.     print("Изменения применены. Не забудьте сохранить базу данных!")
  384.   else
  385.     print("Изменения утеряны.")
  386.   end
  387.   os.sleep(1)
  388. end
  389.  
  390. updateList()
  391. ::main::
  392. while true do
  393.   local mode = nil
  394.   repeat
  395.     term.clear()
  396.     term.setCursor(1, 1)
  397.     print("БД: " .. FILE)
  398.     print(" [0] Выход")
  399.     print(" [1] Добавление рецепта")
  400.     print(" [2] Удаление рецепта")
  401.     print(" [3] Изменение рецепта")
  402.     print(" [4] Сохранение изменений")
  403.     print(" [5] Обновить список")
  404.     print(" [6] Показать информацию о рецепте")
  405.     print(" [7] Сканирование рецепта")
  406.     io.write("Выберите действие: ")
  407.     mode = term.read()
  408.   until tonumber(mode) ~= nil and tonumber(mode) < 8 and tonumber(mode) > -1
  409.  
  410.   mode = tonumber(mode)
  411.  
  412.   if mode == 0 then
  413.     term.clear()
  414.     term.setCursor(1, 1)
  415.     os.exit()
  416.   elseif mode == 1 then
  417.     addRecipe()
  418.   elseif mode == 2 then
  419.     delRecipe()
  420.   elseif mode == 3 then
  421.     addRecipe(true)
  422.   elseif mode == 4 then
  423.     saveAll()
  424.   elseif mode == 5 then
  425.     updateList()
  426.   elseif mode == 6 then
  427.     showRecipe()
  428.   elseif mode == 7 then
  429.     scanRecipe()
  430.   end
  431. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement