• TibiaFace

    Tibiaface | Una comunidad Open Tibia donde encontras : mapas, scripts, Otserver, npc y amigos etc ...

    .
    demo menumenu

    Afiliados



    Votar:

    [Sistema] Simple Crafting System (Tfs 1.2 posible funcionamiento en TFS 1.3)

    Compartir:

    Ver el tema anterior Ver el tema siguiente Ir abajo  Mensaje (Página 1 de 1.)

    [Admin] God Maya

    [Admin] God Maya
    Administrador
    Administrador
    Hola usuarios de tibiaface

    este es un sistema para crear items mediante la recoleccion de objetos o ingredientes que te entregue cada opcion.

    imagenes como se muestra el sistema:

    main por vocation

    [Sistema] Simple Crafting System (Tfs 1.2 posible funcionamiento en TFS 1.3) 365ab710

    seleccion del item

    [Sistema] Simple Crafting System (Tfs 1.2 posible funcionamiento en TFS 1.3) 37c6bb10

    Un ves seleccionado el item no muestra los ingredientes

    [Sistema] Simple Crafting System (Tfs 1.2 posible funcionamiento en TFS 1.3) 6e831a10

    ¿Por qué usar esto?
    Mucho más limpio que todos los otros sistemas de creación ... fácil de configurar y solo necesita agregar el script de acción y los archivos lib. ¡No es necesario registrar los scripts en login.lua o agregar creaturescripts!

    Información sobre el sistema.
    ¡Tiene una sección de configuración fácil para que la personalices como te gustaría! Solo debe completar la tabla de configuración que se encuentra en el script de acción (que se muestra a continuación)

    Código:

    -- Configuracoes de Crafting
        system = {
        [1] = {vocation = "Master Wizard", -- Isto e apenas uma categoria, nao influencia em nada
                items = {
                    [1] = {item = "arcane staff", -- item name (O NOME TEM QUE SER EXATO, SENAO NAO FUNCIONA!)
                            itemID = 2453, -- ID do item que sera feito, tem que ser compativel com o nome acima
                            reqItems = { -- items e quantidade dos items necessarios para craftar
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },


    Instalacion:

    en data/actions/actions.xml agregar esta linea

    Código:
    <action itemid="ITEMID" script="crafting.lua"/>

    ITEMID ----> cambie por un id de un objeto que no se mueva

    Ahora nos vamos a /data/actions/scripts y crean un archivo llamado crafting.lua

    Código:

    local config = {
    -- Configuracao da Janela Modal
        mainTitleMsg = "Crafting System", -- TITUTLO DA JANELA QUE ABRE
        mainMsg = "Welcome to the crafting system. Please choose a vocation to begin.", -- MENSAGEM DA JANELA
     
        craftTitle = "Crafting System: ", -- Titulo da tela de craft apos o player selecionar a vocacao destinada dos items
        craftMsg = "Here is a list of all items that can be crafted for the ", -- Mensagem na tela de craft após escolhas do jogador de vocação
    -- Fim da config Janela Modal
     
    -- Notificacoes ao player
        needItems = "You do not have all the required items to make ", -- Mensagem que aparece quando o player tenta craftar e nao tem todos os items
     
    -- Configuracoes de Crafting
        system = {
        [1] = {vocation = "Master Wizard", -- Isto e apenas uma categoria, nao influencia em nada
                items = {
                    [1] = {item = "arcane staff", -- item name (O NOME TEM QUE SER EXATO, SENAO NAO FUNCIONA!)
                            itemID = 2453, -- ID do item que sera feito, tem que ser compativel com o nome acima
                            reqItems = { -- items e quantidade dos items necessarios para craftar
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                     
                    [2] = {item = "enchanted spear",
                            itemID = 7367,   
                            reqItems = {
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                       },
                },
                
       [2] = {vocation = "Elder Wizard",
                items = {
                    [1] = {item = "arcane staff",
                            itemID = 2453,
                            reqItems = {
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                     
                    [2] = {item = "enchanted spear",
                            itemID = 7367,   
                            reqItems = {
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                       },
                },         
                
       [3] = {vocation = "Swift Archer",
                items = {
                    [1] = {item = "arcane staff",
                            itemID = 2453,
                            reqItems = {
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                     
                    [2] = {item = "enchanted spear",
                            itemID = 7367,   
                            reqItems = {
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                       },
                },         
             
       [4] = {vocation = "Guardian Warrior",
                items = {
                    [1] = {item = "arcane staff",
                            itemID = 2453,
                            reqItems = {
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                     
                    [2] = {item = "enchanted spear",
                            itemID = 7367,   
                            reqItems = {
                                    [1] = {item = 9969, count = 1}, -- Black Skull
                                    [2] = {item = 5904, count = 30}, -- Magic Sulphur
                                },
                            },
                       },
                },      
                            
             },
                  
          }
          
                 
    local player = Player(cid)
    function onUse(player, item, fromPosition, itemEx, toPosition, isHotkey)

          player:sendMainCraftWindow(config)

       return true
    end


    Ahora en la carpeta Data/ global.lua agregamos esto al incio de scripts

    Código:
    dofile('data/lib/crafting.lua')

    Despues nos vamos a /data/lib/ creamos un archivo llamado crafting.lua y pegamos esto dentro

    Código:

    -- Main Crafting Window -- This is the modal window that is displayed first
    function Player:sendMainCraftWindow(config)
     local function buttonCallback(button, choice)

     -- Modal Window Functionallity
     if button.text == "Select" then
     self:sendVocCraftWindow(config, choice.id)
     end
     end
     
     -- Modal window design
     local window = ModalWindow {
     title = config.mainTitleMsg, -- Title of the main craft modal window
     message = config.mainMsg.."\n\n" -- Message of the main craft modal window
     }

     -- Add buttons to the window (Note: if you change the names of these you must change the functions in the modal window functionallity!)
     window:addButton("Select", buttonCallback)
     window:addButton("Exit", buttonCallback)
     
     -- Add choices from the action script
        for i = 1, #config.system do
     window:addChoice(config.system[i].vocation)
        end

     -- Set what button is pressed when the player presses enter or escape.
     window:setDefaultEnterButton("Select")
     window:setDefaultEscapeButton("Exit")
     
     -- Send the window to player
     window:sendToPlayer(self)
    end
    -- End of the first modal window



    -- This is the modal window that displays all avalible items for the chosen vocation.
    function Player:sendVocCraftWindow(config, lastChoice)
        local function buttonCallback(button, choice)

    -- Modal Window Functionallity
     -- If the user presses the back button they will be redirected to the main window.
     if button.text == "Back" then
     self:sendMainCraftWindow(config)
     end
     -- If the user presses the details button they will be redirected to a text window with information about the item they want to craft.
     if button.text == "Details" then
     local item = config.system[lastChoice].items[choice.id].item
     local details = "In order to craft "..item.." you must collect the following items.\n\nRequired Items:"

     for i = 1, #config.system[lastChoice].items[choice.id].reqItems do
     local reqItems = config.system[lastChoice].items[choice.id].reqItems[i].item
     local reqItemsCount = config.system[lastChoice].items[choice.id].reqItems[i].count
     local reqItemsOnPlayer = self:getItemCount(config.system[lastChoice].items[choice.id].reqItems[i].item)
     details = details.."\n- "..capAll(getItemName(reqItems).." ["..reqItemsOnPlayer.."/"..reqItemsCount.."]")
     end
     
     self:showTextDialog(item, details)
     self:sendVocCraftWindow(config, lastChoice)
     end
     
     -- if the player presses the craft button then begin checks.
     if button.text == "Craft" then
     
     -- Check if player has required items to craft the item. If they dont send needItems message.
     for i = 1, #config.system[lastChoice].items[choice.id].reqItems do
     if self:getItemCount(config.system[lastChoice].items[choice.id].reqItems[i].item) < config.system[lastChoice].items[choice.id].reqItems[i].count then
     self:say(config.needItems..config.system[lastChoice].items[choice.id].item, TALKTYPE_MONSTER_SAY)
     return false
     end
     end
     -- Remove the required items and there count from the player.
     for i = 1, #config.system[lastChoice].items[choice.id].reqItems do
     self:removeItem(config.system[lastChoice].items[choice.id].reqItems[i].item, config.system[lastChoice].items[choice.id].reqItems[i].count)
     end
     -- Send effect and give player item.
     self:addItem(config.system[lastChoice].items[choice.id].itemID)
     self:getPosition():sendMagicEffect(CONST_ME_FIREATTACK)
     end
        end
     
     -- Modal window design
        local window = ModalWindow {
            title = config.craftTitle..config.system[lastChoice].vocation, -- The title of the vocation specific window
            message = config.craftMsg..config.system[lastChoice].vocation..".\n\n", -- The message of the vocation specific window
        }
     
     -- Add buttons to the window (Note: if you change the names of these you must change the functions in the modal window functionallity!)
     window:addButton("Back", buttonCallback)
     window:addButton("Exit")
     window:addButton("Details", buttonCallback)
     window:addButton("Craft", buttonCallback)
     
     -- Set what button is pressed when the player presses enter or escape
        window:setDefaultEnterButton("Craft")
        window:setDefaultEscapeButton("Exit")
      
     -- Add choices from the action script
        for i = 1, #config.system[lastChoice].items do
            window:addChoice(config.system[lastChoice].items[i].item)
        end
        
     -- Send the window to player
        window:sendToPlayer(self)
    end

    nos vamos a data/creaturescript/creaturescript.xml y agregamos

    Código:
    <event type="modalwindow" name="ModalWindowHelper" script="modalwindowhelper.lua" />

    ahora nos vamos a data/creaturescript/scripts/ y creamos un archivo llamado modalwindowhelper.lua

    Código:

    function onModalWindow(player, modalWindowId, buttonId, choiceId)
        local modalWindow
        for _, window in ipairs(modalWindows.windows) do
            if window.id == modalWindowId then
                modalWindow = window
                break
            end
        end
     
        if not modalWindow then
            return true
        end
     
        local playerId = player:getId()
        if not modalWindow.players[playerId] then
            return true
        end
        modalWindow.players[playerId] = nil
     
        local choice = modalWindow.choices[choiceId]
     
        for _, button in ipairs(modalWindow.buttons) do
            if button.id == buttonId then
                local callback = button.callback or modalWindow.defaultCallback
                if callback then
                    callback(button, choice)
                    break
                end
            end
        end
     
        return true
    end


    ahora lo ultimo nos vamos a data/global.lua y agregamos a final de ese archivo esto:

    Código:

    function capAll(str)
        local newStr = ""; wordSeparate = string.gmatch(str, "([^%s]+)")
        for v in wordSeparate do
            v = v:gsub("^%l", string.upper)
            if newStr ~= "" then
                newStr = newStr.." "..v
            else
                newStr = v
            end
        end
        return newStr
    end


    if not modalWindows then
        modalWindows = {
            modalWindowConstructor = ModalWindow,
            nextFreeId = 500,
     
            windows = {}
        }
    end
     
    local MT = {}
    MT.__index = MT
     
    function ModalWindow(...)
        local args = {...}
        if type(args[1]) == 'table' then
            local self = setmetatable(args[1], MT)
            local id = modalWindows.nextFreeId       
            self.id = id
            self.buttons = {}
            self.choices = {}
            self.players = {}
            self.created = false
     
            modalWindows.nextFreeId = id + 1
            table.insert(modalWindows.windows, self)
            return self
        end
     
        return modalWindows.modalWindowConstructor(...)
    end
     
    function MT:setDefaultCallback(callback)
        self.defaultCallback = callback
    end
     
    function MT:addButton(text, callback)
        local button = {text = tostring(text), callback = callback}
        table.insert(self.buttons, button)
        return button
    end
     
    function MT:addButtons(...)
        for _, text in ipairs({...}) do
            table.insert(self.buttons, {text = tostring(text)})
        end
    end
     
    function MT:addChoice(text)
        local choice = {text = tostring(text)}
        table.insert(self.choices, choice)
        return choice
    end
     
    function MT:addChoices(...)
        for _, text in ipairs({...}) do
            table.insert(self.choices, {text = tostring(text)})
        end
    end
     
    function MT:setDefaultEnterButton(text)
        self.defaultEnterButton = text
    end
     
    function MT:setDefaultEscapeButton(text)
        self.defaultEscapeButton = text
    end
     
    function MT:setTitle(title)
        self.title = tostring(title)
    end
     
    function MT:setMessage(message)
        self.message = tostring(message)
    end
     
    local buttonOrder = {
        [4] = {3, 4, 2, 1},
        [3] = {2, 3, 1},
        [2] = {1, 2},
        [1] = {1}
    }
    function MT:create()
        local modalWindow = modalWindows.modalWindowConstructor(self.id, self.title, self.message)
        local order = buttonOrder[math.min(#self.buttons, 4)]
     
        if order then
            for _, i in ipairs(order) do
                local button = self.buttons[i]
                modalWindow:addButton(i, button.text)
                button.id = i
     
                if button.text == self.defaultEnterButton then
                    modalWindow:setDefaultEnterButton(i)
                elseif button.text == self.defaultEscapeButton then
                    modalWindow:setDefaultEscapeButton(i)
                end
            end
        end
     
        for _, choice in ipairs(self.choices) do
            modalWindow:addChoice(_, choice.text)
            choice.id = _
        end
     
        self.modalWindow = modalWindow
    end
     
    function MT:sendToPlayer(player)
        if not self.modalWindow then
            self:create()
        end
     
        player:registerEvent('ModalWindowHelper')
        self.players[player:getId()] = true
        return self.modalWindow:sendToPlayer(player)
    end

    y listo



    Última edición por [Admin] God Maya el Lun Nov 04, 2019 8:11 am, editado 1 vez



    [Sistema] Simple Crafting System (Tfs 1.2 posible funcionamiento en TFS 1.3) YNU5B25
    4 participantes
    http://www.tibiaface.com

    zaraza

    zaraza
    Miembro
    Miembro
    hola que tal, sabes que estoy teniendo este error cuando trato de usar el item que puse para que sea el action ID

    Lua Script Error: [Action Interface]
    data/actions/scripts/crafting.lua:onUse
    data/actions/scripts/crafting.lua:257: attempt to call method 'sendMainCraftWindow' (a nil value)
    stack traceback:
           [C]: in function 'sendMainCraftWindow'
           data/actions/scripts/crafting.lua:257: in function <data/actions/scripts/crafting.lua:256>

    desde ya muchas gracias, espero una respuesta correcta

    Estoy utilizando TFS 1.2

    4 participantes

    [Admin] God Maya

    [Admin] God Maya
    Administrador
    Administrador
    zaraza escribió:hola que tal, sabes que estoy teniendo este error cuando trato de usar el item que puse para que sea el action ID

    Lua Script Error: [Action Interface]
    data/actions/scripts/crafting.lua:onUse
    data/actions/scripts/crafting.lua:257: attempt to call method 'sendMainCraftWindow' (a nil value)
    stack traceback:
           [C]: in function 'sendMainCraftWindow'
           data/actions/scripts/crafting.lua:257: in function <data/actions/scripts/crafting.lua:256>

    desde ya muchas gracias, espero una respuesta correcta

    Estoy utilizando TFS 1.2

    listo dejeme revisar el sistema mas seguro me falto contenido, lo solucion en el transcurso del dia lo etiquetare en una nueva respuesta



    [Sistema] Simple Crafting System (Tfs 1.2 posible funcionamiento en TFS 1.3) YNU5B25
    4 participantes
    http://www.tibiaface.com

    [Admin] God Maya

    [Admin] God Maya
    Administrador
    Administrador
    [Tienes que estar registrado y conectado para ver este vínculo]


    sistema actualizado porfavor revisar el tema principal y vea que se añadieron nuevos pasos para que no marque error en su funcionamiento



    [Sistema] Simple Crafting System (Tfs 1.2 posible funcionamiento en TFS 1.3) YNU5B25
    4 participantes
    http://www.tibiaface.com

    Sotomallor

    Sotomallor
    Miembro
    Miembro
    funciona para tfs 0.4 dev? saludos

    4 participantes

    daeks

    daeks
    Nuevo Miembro
    Nuevo Miembro
    Lo podrias adaptar a tfs 0.4 o 0.3 o otx2

    4 participantes

    Contenido patrocinado


    4 participantes

    Ver el tema anterior Ver el tema siguiente Volver arriba  Mensaje (Página 1 de 1.)

    Permisos de este foro:
    No puedes responder a temas en este foro.

     

    BienvenidosTibiaFace es una comunidad de Open Tibia. Para participar debes estar registrado (click para Regístrate).