Перейти к содержимому

serafim

Пользователи
  • Публикации

    367
  • Зарегистрирован

  • Посещение

  • Победитель дней

    46

Сообщения, опубликованные пользователем serafim


  1. Да можно, но нужно учесть что при каждом вызове будет повторно обрабатываться одна и таже информация, что при опросе ме сети будет вызывать нагрузку, надо бы её за ранее подготавливать

     

    пример с выводом ТПС игрокам из списка

    Скрытый текст
    
    local fs = require("filesystem")
    local com = require("component")
    local bridge = com.openperipheral_bridge
    
    local players = {"Morisonsa","serafim7","Panther666"}
    local TC = 1 -- частота опроса сек
    local TPS = 0
    
    function timestamp()
      local fl = io.open("/time","w")
      fl:close()
      return(fs.lastModified("/time"))
    end
    
    local function glass(surface)
      surface.clear()
      surface.addText(20, 5, "TPS: "..TPS, 0x5BF5F5)
    end
    
    bridge.clear()
    bridge.sync()
    
    while true do
      local RO = timestamp()
      os.sleep(TC)
      local RN = timestamp()
      local RD = 20000 * TC / (RN - RO)
      TPS = tonumber(string.format("%.2f",RD):sub(1,4))
      for i = 1, #players do
        local surface = bridge.getSurfaceByName(players[i])
        if surface then
          glass(surface)
        end
      end
      bridge.sync()
    end

     

     

    • Нравится 2

  2. Если уголь в слоте 1 поддерживается трубой, в таком случае желательно там оставлять 1 уголь, чтоб он заменился на что то другое.

    local component = require("component")
    local robot = require("robot")
    local computer = require("computer")
    
    local generator = component.generator
    
    robot.select(16)
    
    while true do
      if computer.energy() / computer.maxEnergy() < 0.20 and robot.count(1) > 1 then
        robot.select(1)
        generator.insert(1)
        robot.select(16)
      end
      robot.use()
    end 

    Также можно не проверять если уголь в генераторе, если энергия упала ниже 20 %, то там пусто

    • Нравится 3

  3. 1 час назад, _bongo_ сказал:

    Я сделал print(stack), и там опять эта ссылка

    print(stack.name)   .name - это индекс в таблице

    пример как разобрать таблицу дали выше

    for k,v in pairs(stack) do
      print(k,v)
    end

    также можно получить значения с помощью команды, один это номер слота

    lua

    =component.inventory_controller.getStackInInternalSlot(1)

    или добавим .name

    =component.inventory_controller.getStackInInternalSlot(1).name

     

    можно скопировать код и вставить его в компик нажав на колёсико мыши (СКМ)


  4. Из живого нашел ток установщик, ссылки увы не работают

    Скрытый текст
    
    ----------------------СТАРТОВЫЕ ПРЕЛЕССССТИ-------------------------
    
    local XSize, YSize = term.getSize()
    local Selector = 1
    local zaderzhka = 0.1
    local progressBarWidth = 20
    local ColorGray = colors.gray
    local ColorLightGray = colors.lightGray
    local ColorDownloadBack = colors.gray
    local ColorDownloadFront = colors.lightGray
    
    -----------СМЕНА ЦВЕТОВОЙ ПАЛИТРЫ, ЕСЛИ МОНИТОР ЧЕРНО-БЕЛЫЙ---------
    
    if not term.isColor() then
    	ColorGray = colors.black
    	ColorLightGray = colors.black
    	ColorDownloadBack = colors.white
    	ColorDownloadFront = colors.black
    end
    
    -----------МАССИВ СО ДАННЫМИ О КАЖДОЙ ПРОГРАММЕ НА ПАСТЕБИНЕ--------
    
    local Data = {
    	--АПИ
    	{["paste"]="vjs77QA6",["path"]="System/API/cluster",["type"]="API",["category"]="APIs"},
    	{["paste"]="LAKBDeQt",["path"]="System/API/zip",["type"]="API",["category"]="APIs"},
    	{["paste"]="TRUJgUme",["path"]="System/API/context",["type"]="API",["category"]="APIs"},
    	{["paste"]="Z2kWNQaJ",["path"]="System/API/config",["type"]="API",["category"]="APIs"},
    	{["paste"]="6gTj9LxN",["path"]="System/API/image",["type"]="API",["category"]="APIs"},
    	{["paste"]="JPYBYVTd",["path"]="System/API/filemanager",["type"]="API",["category"]="APIs"},
    	{["paste"]="D1QiSj9L",["path"]="System/API/windows",["type"]="API",["category"]="APIs"},
    	{["paste"]="2M3z7Ycf",["path"]="System/API/xml",["type"]="API",["category"]="APIs"},
    	{["paste"]="kWNeNPn5",["path"]="System/API/encryptor.cfg",["type"]="API",["category"]="APIs"},
    	{["paste"]="CpTj9QHL",["path"]="System/API/encryptor",["type"]="API",["category"]="APIs"},
    	{["paste"]="ApGP6e6x",["path"]="System/API/syntax",["type"]="API",["category"]="APIs"},
    	--СИСТЕМА
    	{["paste"]="1KJcUxPU",["path"]="OS",["type"]="other",["category"]="OS"},
    	{["paste"]="HQ5zT3vG",["path"]="System/OS/Icons/default.png",["type"]="other",["category"]="OS"},
    	{["paste"]="Be0DWVWX",["path"]="System/OS/Icons/folder.png",["type"]="other",["category"]="OS"},
    	{["paste"]="90rS8nxX",["path"]="System/OS/Icons/image.png",["type"]="other",["category"]="OS"},
    	{["paste"]="EupZQv59",["path"]="System/OS/Icons/config.png",["type"]="other",["category"]="OS"},
    	{["paste"]="PhCccHT4",["path"]="System/OS/Icons/os.png",["type"]="other",["category"]="OS"},
    	{["paste"]="eWMNUsb6",["path"]="System/OS/Icons/zip.png",["type"]="other",["category"]="OS"},
    	{["paste"]="0rMSM2x2",["path"]="System/OS/Icons/disk.png",["type"]="other",["category"]="OS"},
    	--ДОПОЛНЕНИЯ К ПРИЛОЖЕНИЯМ
    	{["paste"]="J4tPebM0",["path"]="System/MineCode/logo.png",["type"]="other",["category"]="MineCode IDE"},
    	{["paste"]="kAjvzgRN",["path"]="System/MineCode/syntax_colors.cfg",["type"]="other",["category"]="MineCode IDE"},
    	{["paste"]="yT9eRQu9",["path"]="System/Photoshop/pslogo.png",["type"]="other",["category"]="Photoshop"},
    	--ОБЫЧНЫЕ ПРИЛОЖЕНИЯ
    	{["paste"]="qDczAPkV",["path"]="Applications/Cobblestone",["type"]="other",["category"]="applications"},
    	{["paste"]="dkvshvvL",["path"]="Applications/RednetSpy",["type"]="other",["category"]="applications"},
    	--{["paste"]="hUVMQFGU",["path"]="Applications/RednetSend",["type"]="other",["category"]="applications"},
    	--{["paste"]="QqpHrszL",["path"]="Applications/View",["type"]="other",["category"]="applications"},
    	{["paste"]="x824frsu",["path"]="Applications/Transfer",["type"]="other",["category"]="applications"},
    	{["paste"]="pMSt4K2K",["path"]="Applications/Reactor",["type"]="other",["category"]="applications"},
    	{["paste"]="W7ucXtTm",["path"]="Applications/Mine",["type"]="other",["category"]="applications"},
    	{["paste"]="Sexqhkdq",["path"]="Applications/Grief",["type"]="other",["category"]="applications"},
    	{["paste"]="Bsv3iBiN",["path"]="Applications/CBPaint",["type"]="other",["category"]="applications"},
    	{["paste"]="HJg7u7ui",["path"]="Applications/Calibrate",["type"]="other",["category"]="applications"},
    	{["paste"]="Xn8THcUC",["path"]="Applications/About",["type"]="other",["category"]="applications"},
    	--{["paste"]="uQCTsyd6",["path"]="Applications/MenuDemo1",["type"]="other",["category"]="applications"},
    	--{["paste"]="8PL6sQf7",["path"]="Applications/MenuDemo2",["type"]="other",["category"]="applications"},
    	--{["paste"]="g0VdnK3X",["path"]="Applications/FileDemo",["type"]="other",["category"]="applications"},
    	--НОВЫЕ СУПЕР-ХИТРОЖОПЫЕ ПРИЛОЖЕНИЯ
    
    
    	{["paste"]="iDuJCAPS",["icon"]="LVeGQ7pU",["path"]="AirDrop",["type"]="Application",["category"]="applications"},
    	{["paste"]="sXj77Y2B",["icon"]="764jWGZX",["path"]="NewsTicker",["type"]="Application",["category"]="applications"},
    	{["paste"]="sfY8Hwwb",["icon"]="rc2sddVB",["path"]="Pastebin",["type"]="Application",["category"]="applications"},
    	{["paste"]="gt9f7EfZ",["icon"]="sj5uhGUz",["path"]="BSOD",["type"]="Application",["category"]="applications"},
    	{["paste"]="D8hSLB2L",["icon"]="DZjpMD68",["path"]="CodeDoor",["type"]="Application",["category"]="applications"},
    	{["paste"]="4nFps3sF",["icon"]="PA9HFXnX",["path"]="MineCode",["type"]="Application",["category"]="applications"},
    	{["paste"]="CBvTqxRj",["icon"]="hm1jMLhc",["path"]="Photoshop",["type"]="Application",["category"]="applications"},
    	{["paste"]="hHum7Qqb",["icon"]="mMhJSh7x",["path"]="Graph",["type"]="Application",["category"]="applications"},
    }
    
    ----------------------ОБЪЯВЛЕНИЕ ФУНКЦИЙ-----------------------
    
    --ЗАГРУЗКА ФАЙЛОВ С ПАСТЕБИНА
    local function pastebin(paste,path)
            local file = http.get("http://pastebin.com/raw.php?i="..paste)
    	if file then
            	file = file.readAll()
            	h=fs.open(path,"w")
           		h.write(file)
            	h.close()
    	else
    		error("Pastebin server is not aviable.")
    	end
    end
    
    --ЗАГРУЗИТЬ КОНКРЕТНОЕ ПРИЛОЖЕНИЕ
    local function downloadApp(pasteApp,pasteIcon,path)
    	fs.delete(path..".app")
    	pastebin(pasteApp,path..".app/main")
    	pastebin(pasteIcon,path..".app/Resources/icon.png")
    end
    
    --ПРОСТАЯ ЗАЛИВКА ЭКРАНА ЦВЕТОМ
    local function clearScreen(color)
    	term.setBackgroundColor(color)
    	term.clear()
    end
    
    --ПЛАВНОЕ ВКЛЮЧЕНИЕ ЭКРАНА
    local function fadeIn(time)
    	clearScreen(ColorGray)
    	sleep(time)
    	clearScreen(ColorLightGray)
    	sleep(time)
    	clearScreen(colors.white)
    	sleep(time)
    end
    
    --ПЛАВНОЕ ЗАТУХАНИЕ ЭКРАНА
    local function fadeOut(time)
    	clearScreen(ColorLightGray)
    	sleep(time)
    	clearScreen(ColorGray)
    	sleep(time)
    	clearScreen(colors.black)
    	sleep(time)
    	term.setCursorPos(1,1)
    	term.setTextColor(colors.white)
    end
    
    --УНИВЕРСАЛЬНАЯ ФУНКЦИЯ ДЛЯ ОТОБРАЖЕНИЯ ТЕКСТА ПО ЦЕНТРУ ЭКРАНА
    local function centerText(how,coord,text,textColor,backColor)
    	term.setTextColor(textColor)
    	term.setBackgroundColor(backColor)
    	if how == "xy" then
    		term.setCursorPos(math.floor(XSize/2-#text/2),math.floor(YSize/2))
    	elseif how == "x" then
    		term.setCursorPos(math.floor(XSize/2-#text/2),coord)
    	elseif how == "y" then
    		term.setCursorPos(coord,math.floor(YSize/2))
    	end
    	term.write(text)
    end
    
    --НАРИСОВАТЬ ГОРЗОНТАЛЬНУЮ ЛИНИЮ УКАЗАННОЙ ДЛИНЫ И ЦВЕТА
    local function horisontalBar(x,y,width,color)
    	for i=x,(x+width-1) do
    		paintutils.drawPixel(i,y,color)
    	end
    end
    
    --ОТОБРАЖЕНИЕ ШКАЛЫ ЗАГРУЗКИ С ПРОГРЕССОМ В ПРОЦЕНТАХ
    local function progressBar(size,action,percent)
    	local doneSize = math.ceil(percent/100*size)
    	local startingY = math.floor(YSize/2-1)
    	local startingX = math.floor(XSize/2-size/2)
    	horisontalBar(1,startingY,XSize,colors.white)
    	centerText("x",startingY,"Installing "..action,ColorGray,colors.white)
    	horisontalBar(startingX,startingY+2,size,ColorDownloadBack)
    	horisontalBar(startingX,startingY+2,doneSize,ColorDownloadFront)
    	sleep(zaderzhka)
    end
    
    --ЗАГРУЗИТЬ ВСЕ ФАЙЛЫ С ПАСТЕБИНА
    local function downloadAll()
    	clearScreen(colors.white)
    	progressBar(progressBarWidth,"started",0)
    
    	fs.makeDir("Applications")
    	fs.makeDir("System")
    	--fs.makeDir("Documents")
    	--fs.makeDir("Images")
    	--fs.makeDir("Documents/MineCode")
    
    	local oneFileIsHowMuchPercent = 1/#Data*100
    
    	for i=1,#Data do
    		if Data[i]["type"] == "Application" then
    			downloadApp(Data[i]["paste"],Data[i]["icon"],Data[i]["path"])
    		else
    			pastebin(Data[i]["paste"],Data[i]["path"])
    		end
    		progressBar(progressBarWidth,Data[i]["category"],i*oneFileIsHowMuchPercent)
    	end
    
    	clearScreen(colors.white)
    	centerText("x",math.floor(YSize/2),"Done.",ColorLightGray,colors.white)
    	os.pullEvent("key")
    end
    
    --ЗАГРУЗИТЬ ВСЕ АПИ
    local function downloadAPIs()
    	for i=1,#Data do
    		if Data[i]["type"] == "API" then
    			pastebin(Data[i]["paste"],Data[i]["path"])
    		end
    	end
    end
    
    --УДАЛИТЬ ВСЕ МОИ ФАЙЛЫ
    local function deleteOld()
    	fs.delete("Applications")
    	fs.delete("Documents")
    	fs.delete("Images")
    	fs.delete("System")
    	fs.delete("OS")
    	fs.delete("MineCode")
    	fs.delete("startup")
    	fs.delete("Startup")
    end
    
    --УДАЛИТЬ ВООБЩЕ ВСЕ ФАЙЛЫ
    local function deleteAll()
    	local fileList = fs.list("")
    	for i=1,#fileList do
    		if not fs.isReadOnly(fileList[i]) then
    			fs.delete(fileList[i])
    		end
    	end
    end
    
    --НАРИСОВАТЬ СЕЛЕКТОР ДЛЯ ВЫБОРА ПРИ СТАРТЕ ПРОГРАММЫ
    local function drawSelection(y,text,id)
    	if id == Selector then
    		horisontalBar(math.floor(XSize/2-8),y,16,ColorLightGray)
    		centerText("x",y,text,colors.white,ColorLightGray)
    	else
    		horisontalBar(math.floor(XSize/2-8),y,16,colors.white)
    		centerText("x",y,text,ColorLightGray,colors.white)
    	end
    end
    
    --ОТОБРАЖЕНИЕ СТАРТОВОГО ИНТЕРФЕЙСА
    local function gui()
    	local startingY = math.floor(YSize/2-2)
    	centerText("x",startingY,"Welcome to ECS installer",ColorGray,colors.white)
    
    	drawSelection(startingY+2,"Install OS",1)
    	drawSelection(startingY+3,"Clear computer",2)
    	drawSelection(startingY+4,"Download API",3)
    	drawSelection(startingY+5,"Exit",4)
    end
    
    -----------------------СТАРТ ПРОГРАММЫ-----------------------
    
    fadeIn(0)
    gui()
    
    while true do
    	--ОТСЛЕЖИВАНИЕ КЛАВИШ СТРЕЛОК И ENTER
    	local event, scancode = os.pullEvent("key")
    	--ПЕРЕМЕСТИТЬСЯ ВЫШЕ
    	if scancode == 200 then
    		Selector = Selector-1
    		if Selector<1 then Selector=1 end
    		gui()
    	--ПЕРЕМЕСТИТЬСЯ НИЖЕ
    	elseif scancode == 208 then
    		Selector = Selector+1
    		if Selector>4 then Selector=4 end
    		gui()
    	--СКАЧАТЬ ВСЕ С ПАСТЕБИНА
    	elseif scancode == 28 and Selector == 1 then
    		--deleteOld()
    		downloadAll()
    		break
    	--ОЧИСТИТЬ КОМП ОТ МОЕГО ГОВНА
    	elseif scancode == 28 and Selector == 2 then
    		deleteAll()
    		clearScreen(colors.white)
    		centerText("x",math.floor(YSize/2),"Filesystem was cleared.",ColorLightGray,colors.white)
    		local event, scancode = os.pullEvent("key")
    		fadeOut(0)
    		os.reboot()
    		break
    	--СКАЧАТЬ ТОЛЬКО АПИ С ПАСТЕБИНА
    	elseif scancode == 28 and Selector == 3 then
    		fs.delete("System/API")
    		clearScreen(colors.white)
    		centerText("x",math.floor(YSize/2),"Downloading APIs",ColorLightGray,colors.white)
    
    		--[[for i=1,11 do
    			pastebin(Data[i]["paste"],Data[i]["path"])
    		end]]
    		downloadAPIs()
    
    		clearScreen(colors.white)
    		centerText("x",math.floor(YSize/2),"APIs installed in /System/API",ColorLightGray,colors.white)
    		local event, scancode = os.pullEvent("key")
    		break
    	--ВЫЙТИ ИЗ ПРОГРАММЫ
    	elseif scancode == 28 and Selector == 4 then
    		break
    	end
    end
    
    fadeOut(0)
    term.setCursorPos(1,1)

     

     

    • Нравится 1

  5. Так всё норм

     

    в варианте a = {"a","b","c","d","e"}

    индекс в таблице а[1] будет равен а без кавычек

    тип данных string применимо если число нужно записать как текст

     

    Далее код отрабатывает как надо помещая символы в кавычки добавляя их в таблицу t

    то есть данные в таблице будут записаны в виде строки или string

     

    при желании можно на выходе добавлять кавычки

    a = {"a","b","c","d","e"}

    print('"' .. a[1] .. '"')

     


  6. 10 минут назад, rootmaster сказал:

    попробуй вызывать os.sleep(0) только каждые 512 интераций

    Скрытый текст
    
    local computer = require("computer")
    
    local time_start = computer.uptime()
    local count = 0
    for i = 1, 1000 do
      count = count + 1
      if i % 512 == 0 then
        os.sleep(0)
        print("os.sleep(0)")
      end
    end
    print("готово "..os.date("%M:%S",computer.uptime()-time_start))

     

    норм QZ8wyqR.png


  7. Да задержка всё же есть :(

    Пример на 1000 итераций

    local computer = require("computer")
    
    local time_start = computer.uptime()
    local count = 0
    for i = 1, 1000 do
      count = count + 1
      os.sleep(0)
    end
    print("готово "..os.date("%M:%S",computer.uptime()-time_start))

    без слипа

    QZ8wyqR.png

    со слипом

    LYhNd6X.png


  8. 23 минуты назад, rootmaster сказал:

    s.sleep(0.2), раньше вызывался по таймеру на computer.uptime теперь вызывается каждые 512 инструкций интерпретатора моего языка программирования brown, который я сейчас пишу

    можешь попробовать вызывать os.sleep(0) каждую итерацию, теоритически задержка не будет ощутима, но защитит от tlwy


  9. 3afB8ZT.png

     

    Вариант крупного шрифта с поддержкой русской и английской раскладки

     

    набор символов https://pastebin.com/XNLGNrj9  letter.lua

     

    пример использования

    local letter = require("letter")
    local unicode = require("unicode")
    local com = require ("component")
    local gpu = com.gpu
    
    local function print_letters(x,y,txt,color)
      gpu.setForeground(color)
      for i = 1, unicode.len(txt) do
        local sym = unicode.upper(unicode.sub(txt,i,i))
        gpu.set(x,y,letter[sym][1])
        gpu.set(x,y+1,letter[sym][2])
        gpu.set(x,y+2,letter[sym][3])
        x = x + letter[sym][4]
      end
    end
    
    os.execute("cls")
    print_letters(10,10,"привет мир",0x00FF00)

     

    • Нравится 3

  10. поделюсь слегка доработанным монитором онлайна

    Скрытый текст

    FMWujYt.png

    https://pastebin.com/ZQrMhRLW

     

    для более точного отображения времени компик с прогой нужно прогружать, но не обязательно

    прога запоминает временные метки, а счёт времени происходит опираясь на реальное время


  11. Сделал набросок проги

    Скрытый текст
    
    local white_list = {"serafim"}
    local black_list = {"Morisonsa","Elecpat"}
    
    local computer = require("computer")
    local event = require("event").pull
    local com = require('component')
    local gpu = com.gpu
    
    if not com.isAvailable("os_entdetector") then
      error("нет сенсора entity detector")
    end
    
    local sensor = {}
    for address in com.list("os_entdetector") do
      table.insert(sensor,com.proxy(address))
    end
    
    for i = 1,#white_list do
      white_list[white_list[i]] = true
    end
    
    for i = 1,#black_list do
      black_list[black_list[i]] = true
    end
    
    gpu.setResolution(35,15)
    local run = true
     
    local function detector()
      gpu.fill(1,1,35,15," ")
      local count = 0
      local users = {}
      for i = 1,#sensor do
        local pl = sensor[i].scanPlayers(64)
        for j = 1,#pl do
          if not users[pl[j].name] then
            users[pl[j].name] = true
            count = count + 1
            if white_list[pl[j].name] then 
              gpu.setForeground(0x00FF00)
            elseif black_list[pl[j].name] then 
              gpu.setForeground(0xFF0000)
            else 
              gpu.setForeground(0xFFFFFF)
            end 
            gpu.set(2, j+1, j..'. '..pl[j].name)
            gpu.set(25, j+1, ' - '..math.ceil(pl[j].range)..' м')
          end
        end
      end
      gpu.setForeground(0xFFB600)
      gpu.set(2,1, 'В зоне обнаружения радара '..count..' чел.')
      os.sleep(1)
    end
    
    while run do
      pcall(detector)
      local e = {event(1,"key_down")}
      if e[4] == 29 then
        gpu.setResolution(80,25)
        gpu.setBackground(0x000000)
        gpu.setForeground(0xffffff)
        os.execute("cls")
        run = false
        os.exit()
      end
    end

     

    lAYJYN5.png

    По просьбе заказчика добавил поддержку нескольких сенсоров

    Также кнопку выхода Ctrl

    Обернул функцию в pcall чтоб защитить прогу от падения

     

    Для безопасности после запуска в публичном месте, советую снять клавиатуру !

    • Нравится 3

  12. PIM по сути сундук, но используется инвентарь игрока, притом того кто первым станет на него

    Все доступные методы можно получить прогой https://pastebin.com/wGJbJmX4 посути на любое устройство

    Скрытый текст
    
    >> Метод: getInventoryName
    Документация: function():string -- Get the name of this inventory
    >> Метод: destroyStack
    Документация: function(slotNumber:number) -- Destroy a stack
    >> Метод: condenseItems
    Документация: function() -- Condense and tidy the stacks in an inventory
    >> Метод: listMethods
    Документация: function(filterSource:string?):string -- List all the methods available
    >> Метод: expandStack
    Документация: function(stack:{id:string,dmg:number?,qty:number?,...}):table -- Get full stack information from id and/or damage
    >> Метод: type
    Документация: pim
    >> Метод: pushItem
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Push an item from the current inventory into pipe or slot on the other inventory. Returns the amount of items moved
    >> Метод: pullItem
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Pull an item from a slot in another inventory into a slot in this one. Returns the amount of items moved
    >> Метод: getInventorySize
    Документация: function():number -- Get the size of this inventory
    >> Метод: pullItemIntoSlot
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Pull an item from a slot in another inventory into a slot in this one. Returns the amount of items moved
    >> Метод: doc
    Документация: function(method:string):string -- Brief description of method
    >> Метод: getStackInSlot
    Документация: function(slotNumber:number,proxy:boolean?):object -- Get details of an item in a particular slot
    >> Метод: pushItemIntoSlot
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Push an item from the current inventory into pipe or slot on the other inventory. Returns the amount of items moved
    >> Метод: slot
    Документация: -1
    >> Метод: getAllStacks
    Документация: function(proxy:boolean?):table -- Get a table with all the items of the chest
    >> Метод: listSources
    Документация: function():table -- List all method sources
    >> Метод: getAdvancedMethodsData
    Документация: function(method:string?):table -- Get a complete table of information about all available methods
    >> Метод: swapStacks
    Документация: function(from:number,to:number,fromDirection:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN}?,fromDirection:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN}?) -- Swap two slots in the inventory
    >> Метод: address
    Документация: 5456e6f1-48bd-40e2-904a-49d5bf4fd6a6

     

    До написания программы можно опробовать методы в действии

    lua
    =component.pim.getInventoryName()

    Получим ник того кто стоит на pim, если нет ни кого то вернёт значение равное "pim"

    lua
    =component.pim.getAllStacks(0)

    Тут получим значения всех ячеек инвентаря одним запросом в виде таблицы

     

    Упрощённый пример изъятия денег (Железных блоков) в МЕ интерфейс который стоит под пим

    Скрытый текст
    
    local takeMoney = "10"
    local money = "minecraft:iron_block"
    
    local com = require('component')
    local pim = com.pim
    
    local take = 0
    local data = pim.getAllStacks(0)
    for i = 1,36 do
      if data[i] then
        if data[i].id == money then
          local push = pim.pushItem("DOWN",i,takeMoney-take) or 0
          take = take + push
          if take >= takeMoney then
            break
          end
        end
      end
    end

     

    Вариант расположения блоков

    Скрытый текст

    GI0hHqt.png

    Но удобнее использовать MFU чтоб убрать торчащие блоки и провода

     

    12 часа назад, Teen_Romance сказал:

    но что такое proxy - я не знаю

    прокси нужен если нужно использовать несколько одинаковых устройств, в данном случае pim всего один

    12 часа назад, Teen_Romance сказал:

    как с ним работать с мэ + ивенты слушать - пока что загадка

    У пим всего 2 ивента

    когда игрок стал на пим "player_on"

    и когда ушёл с него "player_off"

    Пример получения никнейма

    (использовал ивент в виде таблицы, в дальнейшем пригодится для обработки других событий)

    (например нажатия кнопок, касание экрана, и тд)

    Скрытый текст
    
    local event = require("event")
    local name = ""
    
    while true do
      local e = {event.pull()}
      if e[1] == "player_on" then
        name = e[2] or ""
      elseif e[1] == "player_off" then
        name = ""
      end
      print(name)
    end

     

    Так как установлен мод OpenPeripheral для ме доступны новые методы

    Скрытый текст
    
    >> Метод: pushItem
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Push an item from the current inventory into pipe or slot on the other inventory. Returns the amount of items moved
    >> Метод: getInventoryName
    Документация: function():string -- Get the name of this inventory
    >> Метод: getCraftingCPUs
    Документация: function():table -- Get a list of tables representing the available CPUs in the network.
    >> Метод: getAvailableItems
    Документация: function(details:string{NONE,PROXY,ALL}?):table -- Get a list of the stored and craftable items in the network.
    >> Метод: getInterfaceConfiguration
    Документация: function([slot:number]):table -- Get the configuration of the interface.
    >> Метод: getCpus
    Документация: function():table -- Get a list of tables representing the available CPUs in the network.
    >> Метод: getCraftables
    Документация: function([filter:table]):table -- Get a list of known item recipes. These can be used to issue crafting requests.
    >> Метод: getIdlePowerUsage
    Документация: function():number -- Get the idle power usage of the network.
    >> Метод: store
    Документация: function(filter:table, dbAddress:string[, startSlot:number[, count:number]]): Boolean -- Store items in the network matching the specified filter in the database with the specified address.
    >> Метод: getStackInSlot
    Документация: function(slotNumber:number,proxy:boolean?):object -- Get details of an item in a particular slot
    >> Метод: pullItemIntoSlot
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Pull an item from a slot in another inventory into a slot in this one. Returns the amount of items moved
    >> Метод: condenseItems
    Документация: function() -- Condense and tidy the stacks in an inventory
    >> Метод: doc
    Документация: function(method:string):string -- Brief description of method
    >> Метод: type
    Документация: me_interface
    >> Метод: swapStacks
    Документация: function(from:number,to:number,fromDirection:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN}?,fromDirection:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN}?) -- Swap two slots in the inventory
    >> Метод: getAdvancedMethodsData
    Документация: function(method:string?):table -- Get a complete table of information about all available methods
    >> Метод: getMaxStoredPower
    Документация: function():number -- Get the maximum stored power in the network.
    >> Метод: listMethods
    Документация: function(filterSource:string?):string -- List all the methods available
    >> Метод: exportItem
    Документация: function(fingerprint:{id:string,dmg:number?,nbt_hash:string?},direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},maxAmount:number?,intoSlot:number?):table -- Exports the specified item into the target inventory.
    >> Метод: pullItem
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Pull an item from a slot in another inventory into a slot in this one. Returns the amount of items moved
    >> Метод: expandStack
    Документация: function(stack:{id:string,dmg:number?,qty:number?,...}):table -- Get full stack information from id and/or damage
    >> Метод: getItemsInNetwork
    Документация: function([filter:table]):table -- Get a list of the stored items in the network.
    >> Метод: listSources
    Документация: function():table -- List all method sources
    >> Метод: address
    Документация: 961b9645-a905-4a65-be49-9a785af44f8b
    >> Метод: setInterfaceConfiguration
    Документация: function([slot:number][, database:address, entry:number[, size:number]]):boolean -- Configure the interface.
    >> Метод: getAllStacks
    Документация: function(proxy:boolean?):table -- Get a table with all the items of the chest
    >> Метод: pushItemIntoSlot
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN},slot:number,maxAmount:number?,intoSlot:number?):number -- Push an item from the current inventory into pipe or slot on the other inventory. Returns the amount of items moved
    >> Метод: requestCrafting
    Документация: function(fingerprint:{id:string,dmg:number?,nbt_hash:string?},qty:number?,cpu:string?) -- Requests the specified item to get crafted.
    >> Метод: getStoredPower
    Документация: function():number -- Get the stored power in the network. 
    >> Метод: getFluidsInNetwork
    Документация: function():table -- Get a list of the stored fluids in the network.
    >> Метод: getInventorySize
    Документация: function():number -- Get the size of this inventory
    >> Метод: slot
    Документация: -1
    >> Метод: getAvgPowerUsage
    Документация: function():number -- Get the average power usage of the network.
    >> Метод: destroyStack
    Документация: function(slotNumber:number) -- Destroy a stack
    >> Метод: getItemDetail
    Документация: function(item:{id:string,dmg:number?,nbt_hash:string?},proxy:boolean?):object -- Retrieves details about the specified item from the ME Network.
    >> Метод: getAvgPowerInjection
    Документация: function():number -- Get the average power injection into the network.
    >> Метод: canExport
    Документация: function(direction:string{DOWN,UP,NORTH,SOUTH,WEST,EAST,UNKNOWN}):boolean -- Returns true when the interface can export to side.

     

    Например с помощью id можно отправить предмет из МЕ в PIM

    Скрытый текст
    
    local com = require("component")
    local interface = com.me_interface 
    
    local function export(fingerprint,direction,amount)
      local ok, value = pcall(interface.exportItem,fingerprint,direction,amount)
      if ok then
        return value.size
      end
      return 0, value or "error"
    end
    
    print(export({id="minecraft:iron_ingot",dmg=0},"UP",10))

     

    Разумеется есть и иные способы

    • Нравится 3
    • Спасибо 2

  13. В данном коде эту ошибку можно словить по нескольким причинам:

    МЕ сеть без энергии

    В МЕ нет шаблона крафта

    В списке items не верно указано название предмета

     

    Опрос предметов по id оправдан если их немного

    Например для 10 предметов требуется 10 опросов сети, а если предметов больше 500 ?

    Правильней будет получить все предметы сети одним запросом а затем уже разобрать таблицу

     

    Опрос по id также создаёт ещё одну проблему

    в сети могут быть предметы с одинаковым названием но разными nbt

    они будут считатся разными

     

    поделюсь кусочком своего прекрафта решающих эти проблемы, увы целиком не могу

    Скрытый текст
    
    if interface.getStoredPower() == 0 then
        gpu.setForeground(0xFF0000)
        print("ме сеть без энергии")
      else
        local data = interface.getItemsInNetwork()
        if not data or #data == 0 then
          gpu.setForeground(0xFF0000)
          print("в ме сети нет предметов")
        else
          for i = 1,#CraftList do
            stop(0)
            gpu.fill(1,1,w,1," ")
            gpu.setForeground(0xFFFF00)
            gpu.set(1, 1, "проверяю список крафта -")
            gpu.setForeground(0xFF00FF)
            gpu.set(26, 1, i.." / "..#CraftList)
            local storedItem = 0
            for item = 1,#data do
              if data[item] ~= nil then
                if data[item].label == CraftList[i].label then
                  storedItem = storedItem + data[item].size
                end
              end
            end
            if storedItem < CraftList[i].craft then
              local delta = CraftList[i].craft - storedItem
              local craftAmount = delta
              if delta > curMaxRequest then
                craftAmount = curMaxRequest
              end

     

     

    • Нравится 2
×
×
  • Создать...