Ir para conteúdo
  • Cadastre-se

Normal [PEDIDO] Npc Que Troca Nome Do Jogador...


Posts Recomendados

Olá,

 

A Script e simples, eu ate já encontrei aqui no TK! Mais tipo, o jogador fala " Hi " dps " Nome " e o Npc não cobra nada, e ainda não troca o nome.. o Npc que eu quero ele deve coletar o item e trocar o nome do jogador, logo isso relogar.

Mais ou menos assim:

Jogador: Hi

Npc: Olha Fulano, Deseja trocar seu nome por apenas 5 Pontos?

Jogador: Yes

Npc: Ok, Qual o nome Desejado?

Jogador: NooBEmAcAo <<< Apos isso coletar o item e trocar o nome e relogar ( não precisa estar na ordem, eu arrumo )

OBS: BEM EXPLICADO, SOU BURRO!

Quem puder me ajudar dou REP++

 

Obg^^

Editado por MaRqUiiM
Falta de Explicação (veja o histórico de edições)
Link para o post
Compartilhar em outros sites

Ta na mão: Vá em data/npc/scripts e crie um arquivo chamado Troca de Nick.lua e coloque esse Script dentro:

Spoiler

local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local talkState = {}
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
function creatureSayCallback(cid, type, msg)

    if not npcHandler:isFocused(cid) then
        return false
    end
    local talkUser = NPCHANDLER_CONVBEHAVIOR == CONVERSATION_DEFAULT and  or cid
    local item = 2160 						 --ID do item necessario para trocar de nome.
    local characters = {}                    --Configure nesta tabela os caracteres (ou palavras) proibidos.
    local delay = 5                          --Tempo para o jogador ser desconectado após trocar o nome.
    if msgcontains(msg:lower(), "name") or msgcontains(msg:lower(), "change") then
        selfSay("Voce deseja trocar de nome ? Essa troca vai custar 5 {"..getItemNameById(item).."}.", cid)
        talkState[talkUser] = 1
        return true
    elseif msgcontains(msg:lower(), "yes") and talkState[talkUser] == 1 then
        if getPlayerItemCount(cid, item) >= 5 then  -- Quantidade de item que você deseja.
            selfSay("OK, me fale o novo nome que voce deseja.", cid)
            talkState[talkUser] = 2
            return true
        else
            selfSay("Voce nao tem os itens nescessario.", cid)
            talkState[talkUser] = 
            return true
        end
    elseif talkState[talkUser] == 2 then
        local query = db.getResult("SELECT name FROM players")
        if query:getID() == -1 then
            selfSay("Database inexistent.", cid)
            talkState[talkUser] = 
            return true
        end
        repeat
            local name = query:getDataString("name")
            if msg == name then
                selfSay("Esse Nome ja existe.", cid)
                talkState[talkUser] = 
                return true
            end
        until not query:next()
        query:free()
        for i = 1, #characters do
            if msg:find(characters[i]) then
                selfSay("Desculpe, voce nao pode criar personagem com esse Nick, pois ele e proibido.", cid)
                talkState[talkUser] = 
                return true
            end
        end
        local guid = getPlayerGUID(cid)
        db.executeQuery("UPDATE `players` SET `name` = " .. db.escapeString(msg) .. " WHERE `id` = " .. guid .. " LIMIT 1;")
        doPlayerRemoveMoney(cid, price)
		doPlayerRemoveItem(cid, item, 5) -- quantidade de itens que precisa para se trocar de nome.
        selfSay("Voce trocou seu nome para {"..msg.."}. Em "..delay.." segundo"..(delay > 1 and "s" or "")..", voce sera desconectado.", cid)
        addEvent(function()
            if isPlayer(cid) then
                doRemoveCreature(cid)
            end
        end, delay * 1000)
        talkState[talkUser] = 
        return true
    elseif msgcontains(msg:lower(), "no") and talkState[talkUser] == 1 then
        selfSay("Ok, tchau.", cid)
        talkState[talkUser] = 
        return true
    end
    return true
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())

 

 

Agora vá em: data/npc e crie um arquivo chamado Troca de Nick.xml e coloque isso dentro:

Spoiler

<?xml version="1.0" encoding="UTF-8"?>

<npc name="Troca de Nick" script="data/npc/scripts/changer name.lua" walkinterval="2000" floorchange="0">
	<health now="100" max="100"/>
	<look type="118" head="0" body="0" legs="0" feet="0" addons="0"/>

<parameters>

		<parameter key="message_greet" value="Olá |PLAYERNAME|. Eu posso trocar seu Nick. Diga {Name} ou {Changer} caso queira trocar o seu."/>

			<parameter key="message_farewell" value="Até mais!" />

		<parameter key="message_walkaway" value="Até mais!" />

</parameters>

</npc>

 

 

Agora basta usar... xD

 

Bom dentro do Script coloquei comentários para  você ver onde alterar e o que alterar para ficar a seu gosto. Caso não entenda é só falar...

 

Esse Script peguei aqui no TK, estava para trocar o nick por dinheiro apenas, então alterei para troca por itens, e pela quantidade que você deseja.

 

Qualquer coisa to aqui. ^^

Editado por KotZletY (veja o histórico de edições)

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites

Amigo não entendi o "negócio de 5 pontos", mais editei esse script aqui e traduzi para você usar no caso ele renomeia o player por certo item e quantidade. "CONFIGURAVEL"

 

Em Npc crie um arquivo chamado renameplayers.xml, após isso coloque o seguinte código nele.

<?xml version="1.0" encoding="UTF-8"?>
<npc name="Renomeador" script="renn.lua" walkinterval="0" floorchange="0">
<health now="150" max="150"/>
<look type="299" head="114" body="119" legs="114" feet="114" corpse="2212"/>
<parameters>
<parameter key="message_greet" value="Olá |PLAYERNAME|, Deseja trocar seu nome por apenas 5 Pontos?"/>
</parameters>
</npc>

Em Npc/script crie um arquivo chamado renn.lua, após isso coloque o seguinte código nele.

local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local talk = {}
local name = {}

function onCreatureAppear(cid)			npcHandler:onCreatureAppear(cid)			end
function onCreatureDisappear(cid)		npcHandler:onCreatureDisappear(cid)			end
function onCreatureSay(cid, type, msg)		npcHandler:onCreatureSay(cid, type, msg)		end
function onThink()				npcHandler:onThink()					end
function onPlayerEndTrade(cid) npcHandler:nPlayerEndTrade(cid) end
function onPlayerCloseChannel(cid) npcHandler:nPlayerCloseChannel(cid) end

function creatureGreetCallback(cid)
talk[cid] = 
name[cid] = ''
return true
end

local chars = {' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}

RET_VALID = 1
RET_EXISTS = 2
RET_INVALID = 3

local function validName(name)
if getPlayerGUIDByName(name) ~= nil then
return RET_EXISTS
end

local notAllowed = {"god", "gm", "cm", "tutor", "help", "admin"}
for _, naw in pairs(notAllowed) do
if (name:lower():find(naw .. " ") or name:lower() == naw or name:lower():find("admin")) then
return RET_INVALID
end
end

for i = 1, name:len() do
if not(isInArray(chars, name:sub(i,i))) then
return RET_INVALID
end
end
return RET_VALID
end

local function getValid(name, opt)
local function tchelper(first, rest)
return first:upper()..rest:lower()
end

return opt and name:gsub("(%a)([%w_']*)", tchelper) or name:gsub("^%l", string.upper)
end

local config = {
type = 'item',
money = 10000, -- = ignore
item = {2159, 20}, -- Item, quantidade
everyFirstLetterCapital = true
}

function messageDefaultCallback(cid, type, msg)
if not(npcHandler:isFocused(cid)) then
return false
end

if msgcontains(msg, "yes") and talk[cid] ==  then
selfSay("Ok, Qual o nome Desejado?", cid)
talk[cid] = 1
elseif talk[cid] == 1 then
local v = getValid(msg:lower(), config.everyFirstLetterCapital)
local ret = validName(v)
if ret == RET_VALID then
selfSay("Então você quer '" .. v .. "' para ser seu nickname novo, irá custar: " .. (config.type == "money" and (config.money .. " gold") or (config.item[2] .. ' ' .. (config.item[2] > 1 and getItemPluralNameById(config.item[1]) or getItemNameById(config.item[1])))) .. "?", cid)
talk[cid], name[cid] = 2, v
else
if ret == RET_INVALID then
selfSay(msg .. " Não é um nome válido, diga me outro nome", cid)
elseif ret == RET_EXISTS then
selfSay(msg .. " Já existe diga-me outro nome", cid)
end
end
elseif talk[cid] == 2 then
if msgcontains(msg, "yes") then
if (config.type == 'money' and doPlayerRemoveMoney(cid, config.money)) or (config.type ~= 'money' and doPlayerRemoveItem(cid, config.item[1], config.item[2])) then
local curName = getPlayerName(cid)
doRemoveCreature(cid)
db.executeQuery("UPDATE players SET name = '"..name[cid].."' WHERE name = '"..curName.."';")
else
selfSay("Você não tem 5 Pontos :(", cid)
talk[cid] = 
end
else
selfSay("Talvez mais tarde.", cid)
talk[cid] = 
end
end


return true
end

npcHandler:setMessage(MESSAGE_FAREWELL, "Tchau.")
npcHandler:setMessage(MESSAGE_WALKAWAY, "Até logo!")
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, messageDefaultCallback) 
npcHandler:setCallback(CALLBACK_FAREWELL, creatureFarewell)
npcHandler:setCallback(CALLBACK_CREATURE_DISAPPEAR, creatureFarewell)
npcHandler:setCallback(CALLBACK_GREET, creatureGreetCallback)
npcHandler:addModule(FocusModule:new())

Como configurar: 

 

local config = {  
type = 'item',
-- Não mecha 
money = 10000, -- ignore
item = {2159, 20}, -- Item, quantidade
everyFirstLetterCapital = true

Link para o post
Compartilhar em outros sites
9 minutos atrás, MaRqUiiM disse:

REP++ aos Dois, pois foram os unicos que ajudaram xD

Thankz, mas... Qual você testou e qual conseguiu fazer o que você queria realmente ? :hum:

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites
3 minutos atrás, KotZletY disse:

Thankz, mas... Qual você testou e qual conseguiu fazer o que você queria realmente ? :hum:

estou testanto o seu agora.. o do cara la, o npc nao apareceu no mapa :/

Link para o post
Compartilhar em outros sites
1 minuto atrás, MaRqUiiM disse:

estou testanto o seu agora.. o do cara la, o npc nao apareceu no mapa :/

Para aparecer no mapa, você precisa importa ele para o RME, colocar um Radius no lugar que ele vai ficar, e colocar ele lá. xD

 

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites
1 minuto atrás, KotZletY disse:

Para aparecer no mapa, você precisa importa ele para o RME, colocar um Radius no lugar que ele vai ficar, e colocar ele lá. xD

 

essa parte ae e facil ja fiz, mais nem um dos dois apareceu eu importo pro mapa RME e atualizo o mapa e salvo, ffaço tudo certo, coloco akele bagui paara ele nascer e tals

 

Link para o post
Compartilhar em outros sites
Agora, MaRqUiiM disse:

essa parte ae e facil ja fiz, mais nem um dos dois apareceu eu importo pro mapa RME e atualizo o mapa e salvo, ffaço tudo certo, coloco akele bagui paara ele nascer e tals

 

Estranho cara, coloquei aqui rapidinho em dois tempos funcionou.. Apareci algum erro na Distro ?

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites
1 minuto atrás, KotZletY disse:

Estranho cara, coloquei aqui rapidinho em dois tempos funcionou.. Apareci algum erro na Distro ?

aparece muitos.. mais nem sei qual e'-'

Link para o post
Compartilhar em outros sites
Agora, MaRqUiiM disse:

aparece muitos.. mais nem sei qual e'-'

Eitah... Tira uma print manda aqui pra noiz resolver! 

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites
1 minuto atrás, KotZletY disse:

Eitah... Tira uma print manda aqui pra noiz resolver! 

Esse aqui fica direto soltando...

Screenshot_2.png

Link para o post
Compartilhar em outros sites
13 minutos atrás, MaRqUiiM disse:

Esse aqui fica direto soltando...

Screenshot_2.png

Amigo este erro não é do Npc não :)

Link para o post
Compartilhar em outros sites
16 minutos atrás, MaRqUiiM disse:

Esse aqui fica direto soltando...

Screenshot_2.png

Não é mesmo cara. Até por que a Script não usa a tabela z_ots_comunication.

Editado por KotZletY (veja o histórico de edições)

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites
3 minutos atrás, MySticaL disse:

Amigo este erro não é do Npc não :)

Achei o erro " reen " e o do npc

Screenshot_3.png

2 minutos atrás, KotZletY disse:

Não é mesmo cara. Até por que a Script não usa a tabela z_ots_comunication.

Mais esse aqui e ne?..

Screenshot_3.png

Link para o post
Compartilhar em outros sites

Tenta agora: 

Spoiler

local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local talkState = {}
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
function creatureSayCallback(cid, type, msg)

    if not npcHandler:isFocused(cid) then
        return false
    end
    local talkUser = NPCHANDLER_CONVBEHAVIOR == CONVERSATION_DEFAULT and 
    local item = 2160 						 --ID do item necessario para se torna um ULTRA GOD
    local characters = {}                    --Configure nesta tabela os caracteres (ou palavras) proibidos.
    local delay = 5                          --Tempo para o jogador ser desconectado após trocar o nome.
    if msgcontains(msg:lower(), "name") or msgcontains(msg:lower(), "change") then
        selfSay("Voce deseja trocar de nome ? Essa troca vai custar 5 {"..getItemNameById(item).."}.", cid)
        talkState[talkUser] = 1
        return true
    elseif msgcontains(msg:lower(), "yes") and talkState[talkUser] == 1 then
        if getPlayerItemCount(cid, item) >= 5 then  -- Quantidade de item que você deseja.
            selfSay("OK, me fale o novo nome que voce deseja.", cid)
            talkState[talkUser] = 2
            return true
        else
            selfSay("Voce nao tem os itens nescessario.", cid)
            talkState[talkUser] = 
            return true
        end
    elseif talkState[talkUser] == 2 then
        local query = db.getResult("SELECT name FROM players")
        if query:getID() == -1 then
            selfSay("Database inexistent.", cid)
            talkState[talkUser] = 
            return true
        end
        repeat
            local name = query:getDataString("name")
            if msg == name then
                selfSay("Esse Nome ja existe.", cid)
                talkState[talkUser] = 
                return true
            end
        until not query:next()
        query:free()
        for i = 1, #characters do
            if msg:find(characters[i]) then
                selfSay("Desculpe, voce nao pode criar personagem com esse Nick, pois ele e proibido.", cid)
                talkState[talkUser] = 
                return true
            end
        end
        local guid = getPlayerGUID(cid)
        db.executeQuery("UPDATE `players` SET `name` = " .. db.escapeString(msg) .. " WHERE `id` = " .. guid .. " LIMIT 1;")
        doPlayerRemoveMoney(cid, price)
		doPlayerRemoveItem(cid, item, 5) -- quantidade de itens que precisa para se trocar de nome.
        selfSay("Voce trocou seu nome para {"..msg.."}. Em "..delay.." segundo"..(delay > 1 and "s" or "")..", voce sera desconectado.", cid)
        addEvent(function()
            if isPlayer(cid) then
                doRemoveCreature(cid)
            end
        end, delay * 1000)
        talkState[talkUser] = 
        return true
    elseif msgcontains(msg:lower(), "no") and talkState[talkUser] == 1 then
        selfSay("Ok, tchau.", cid)
        talkState[talkUser] = 
        return true
    end
    return true
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())

 

 

Edit: Tenta agora, coloquei uma coisa errada mais ta certo agora!

Editado por KotZletY (veja o histórico de edições)

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites
4 minutos atrás, MaRqUiiM disse:

Achei o erro " reen " e o do npc

Screenshot_3.png

Você tem certeza que copiou tudo certo, aqui está normal.

Segue a print:

Hg8mABt.png

 

 

Link para o post
Compartilhar em outros sites
Agora, MySticaL disse:

Você tem certeza que copiou tudo certo, aqui está normal.

Segue a print:

Hg8mABt.png

 

 

Tbm acho, então tirei o " or cid " que não tem muita importância.  Testei e ta funcionando perfeitamente! 

                                                              ezgif-1-98aab239f3.gif.1a897c9c3225228909e7b356a5cfb8e4.gif

Link para o post
Compartilhar em outros sites
4 minutos atrás, KotZletY disse:

Tbm acho, então tirei o " or cid " que não tem muita importância.  Testei e ta funcionando perfeitamente! 

pqp deixa para la, vlw pela ajuda acho qe meu dbo nao pega mesmo nao slk

segue o print

 

Screenshot_4.png

Link para o post
Compartilhar em outros sites
2 minutos atrás, MaRqUiiM disse:

pqp deixa para la, vlw pela ajuda acho qe meu dbo nao pega mesmo nao slk

segue o print

 

Screenshot_4.png

Usa o outro então 

Link para o post
Compartilhar em outros sites

Participe da conversa

Você pode postar agora e se cadastrar mais tarde. Se você tem uma conta, faça o login para postar com sua conta.

Visitante
Responder

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emojis são permitidos.

×   Seu link foi automaticamente incorporado.   Mostrar como link

×   Seu conteúdo anterior foi restaurado.   Limpar o editor

×   Não é possível colar imagens diretamente. Carregar ou inserir imagens do URL.

  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.

  • Conteúdo Similar

    • Por ambrozii0
      Gostaria de fazer um pedido de um NPC de Task progressiva,

      Ele iniciaria dando missões para level 8 para caçar Troll, Rotworm e Ghoul.
       
      No level 30 liberaria: Cyclops, Dragon e Wyrm... e assim em diante se puder deixar comentado eu faço as criaturas na sequencia dos leveis seguintes.
       
      O jogador pode fazer as tasks dos leveis anteriores mesmo que já tenha ultrapassado o level do próximo nível de task.
       
      E o jogador ao terminar a missão poderia escolher a recompensa em gold ou experiência. As tasks podem se repetir sem problema, mas apenas pode pegar uma de cada vez.
       
      Ao finalizar todas as tasks o jogador ganha uma montaria.
       
      Minha versão de cliente é 12.91
      Versão da Canary 2.6.1
      Não sei qual o TFS do meu servidor.
    • Por Jaurez
      .
    • Por Cat
      Em alguns casos, o tibia 8.60 comum não abre de jeito nenhum no map editor, mesmo desmarcando check file signatures e configurando o path corretamente.
       
      Este é o client 8.60 adaptado para o Remere's Map Editor. Resolvi postar já que ele foi removido do site oficial do RME. (ficou apenas a versão para linux lá)
      Se estiver tendo problemas para abrir a versão 8.60, tente utilizar este.
                                                                                                                     
      Baixar o Tibia Client 8.60 que funciona no Remere’s Map Editor
      Essa versão do Tibia 8.60 client resolve o erro unsupported client version ou Could not locate tibia.dat and/or tibia.spr, please navigate to your tibia 8.60 installation folder.
       
      Downloads
      https://tibiaking.com/applications/core/interface/file/attachment.php?id=47333

      Scan: https://www.virustotal.com/gui/file/333e172ac49ba2028db9eb5889994509e7d2de28ebccfa428c04e86defbe15cc
       
    • Por Garou
      QUIZ







      Fala, grande reino! Tudo beleza?

      Eu estava aqui a deriva, sem nada para fazer, quando um colega me chamou no msn e pediu para eu revisar um código que ele havia feito para um NPC. A função era bem simples, o tal NPC iria fazer perguntas ao jogador que devia responder-las corretamente, caso errasse, duas criaturas configuráveis iriam aparecer.

      Quando eu dei uma olhada no código, tomei um grande susto, era algo caótico, tudo embaralhado. Se você quer dar uma olhada, tenha certeza de ter um coração forte.



      --[[ NPC de Perguntas e Respostas Criado por Bruno Lopes / Lpz &#169; 2011 TibiaKing ]]-- local focuses = {} local talk_start = 0 local topic = {} local var = 0 local quiz = { [1] = {"What is the ring of mana?", "energy ring"}, [2] = {"Who sells addons?", "raphael"} } local monster = {"Orc", 2} local prize = { question = 100, all = 10000 } function onCreatureSay(cid, type, msg) local msg = msg:lower() or "" if getNpcDistanceTo(cid) > 3 then return false end if doMessageCheck(msg, {"hi", "hello"}) and not(isFocused(cid, focuses)) then selfSay("Hello, ".. getCreatureName(cid) ..". Can you answer my questions? heh...", cid) addFocus(cid, focuses) selfFocus(cid) topic[cid] = 100 talk_start = os.clock() elseif doMessageCheck(msg, {"hi", "hello"}) and #focuses ~= 0 then selfSay("Sorry, ".. getCreatureName(cid) ..". I am talking with another person, wait!", cid) end if doMessageCheck(msg, {"bye", "farewell", "goodbye"}) and isFocused(cid, focuses) then selfSay("Bye-bye, hehe!", cid) removeFocus(cid, focuses) end if topic[cid] == 100 then if doMessageCheck(msg, "yes") then selfSay("To start my challenge, just say {ready}. I will ask you some questions.", cid) topic[cid] = 1 elseif doMessageCheck(msg, "no") then selfSay("Huh? Why are you here then?", cid) removeFocus(cid, focuses) topic[cid] = 0 end elseif topic[cid] == 1 then if var == 0 then if doMessageCheck(msg, "ready") then var = 1 selfSay(quiz[var][1], cid) end elseif var >= 1 then if var <= #quiz then if doMessageCheck(msg, quiz[var][2]) then selfSay("CORRECT!", cid) doPlayerAddMoney(cid, prize.question) var = var+1 if var > #quiz then selfSay("CONGRATULATIONS! YOU HAVE FINISHED ALL QUESTIONS!", cid) doPlayerAddMoney(cid, prize.all) else selfSay(quiz[var][1], cid) end else selfSay("YOU HAVE WRONG MY QUESTION! GUARDS, COME HERE!", cid) var = 0 topic[cid] = 0 removeFocus(cid, focuses) for i = 1, monster[2] do doCreateMonster(monster[1], getNpcPos()) end end end end end return true end function onThink() for _, cid in ipairs(focuses) do if isPlayer(cid) and isFocused(cid, focuses) then if os.clock() > (talk_start + 180) then talk_start = 0 selfSay("Hmph!") closeShopWindow(cid) removeFocus(cid, focuses) elseif getNpcDistanceTo(cid) > 3 then talk_start = 0 selfSay("How Rude!") closeShopWindow(cid) removeFocus(cid, focuses) end end end lookAtFocus(focuses) end Bom, eu fiz o arquivo .lua que você iria associar a algum npc de seu servidor, deixo o arquivo .xml por sua conta. Como é um NPC que faz perguntas, você pode configurar o seu NPC do jeito que você quiser, com as perguntas que você quiser. Veja abaixo como proceder: local quiz = { [1] = {"What is the ring of mana?", "energy ring"}, [2] = {"Who sells addons?", "raphael"} } Para adicionar novas perguntas, basta você colocar uma vírgula na última linha e criar uma nova linha conforme o modelo: local quiz = { [1] = {"What is the ring of mana?", "energy ring"}, [2] = {"Who sells addons?", "raphael"}, [3] = {"PERGUNTA", "RESPOSTA"}, [4] = {"PERGUNTA", "RESPOSTA"} } Há também algumas outras configurações básicas para você fazer, as criaturas que irão aparecer caso o jogador erre a pergunta e a quantidade. Também você pode configurar a quantidade de dinheiro que o jogador ganha quando acerta uma pergunta e a quantidade de dinheiro do prêmio final. local monster = {"Orc", 2} local prize = { question = 100, all = 10000 } OBSERVAÇÕES Para evitar quaisquer erros no script, substitua o conteúdo de npc.lua em data/npc/lib por este que estou passando abaixo:



      É isso aê, galerinha do tibiaKing!

      Até o próximo tópico.
    • Por Codex NG
      Sorry I don't speak spanish so you will have to bare with me.
       
      This is a new way for people to create npc's which use different types of currency, rather than a coming up with different items to trade with the npc or trying to edit the npc modules this method simplifies everything by providing the npc with a npc currency id.
       
      All this npc currency id is, is a storage value.. pretty simple eh?
      If the npc doesn't have a currency id then it will use the normal currency e.g. gold, plat, cc etc..
       
      I originally posted this on otland, but fuck them xD
       
      Using Lailene here you can see she has a currency attribute with id of 123456
      <?xml version="1.0" encoding="UTF-8"?> <npc name="Lailene" currency="123456" script="lailene.lua" walkinterval="2000" floorchange="0" speechbubble="2"> <health now="100" max="100"/> <look type="279" head="114" body="94" legs="113" feet="114" addons="0"/> </npc>  
      Now any player who has a storage value of 123456 can purchase things from her shop provided they have enough value stored within the storage, similar to having money in the bank.
      The money or in this case the storage value is added and removed from the player in real time.
       
      Lets get to the code
       
      game.cpp
      Find this
      bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) Replace the whole function with this.
      bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) { if (cylinder == nullptr) { return false; } if (money == 0) { return true; } uint32_t currencyId = 0; Player* player; if (Creature* creature = cylinder->getCreature()) { if (Player* p = creature->getPlayer()) { currencyId = p->getNpcCurrencyId(); player = p; } } if (!currencyId) { std::vector<Container*> containers; std::multimap<uint32_t, Item*> moneyMap; uint64_t moneyCount = 0; for (size_t i = cylinder->getFirstIndex(), j = cylinder->getLastIndex(); i < j; ++i) { Thing* thing = cylinder->getThing(i); if (!thing) { continue; } Item* item = thing->getItem(); if (!item) { continue; } Container* container = item->getContainer(); if (container) { containers.push_back(container); } else { const uint32_t worth = item->getWorth(); if (worth != 0) { moneyCount += worth; moneyMap.emplace(worth, item); } } } size_t i = 0; while (i < containers.size()) { Container* container = containers[i++]; for (Item* item : container->getItemList()) { Container* tmpContainer = item->getContainer(); if (tmpContainer) { containers.push_back(tmpContainer); } else { const uint32_t worth = item->getWorth(); if (worth != 0) { moneyCount += worth; moneyMap.emplace(worth, item); } } } } if (moneyCount < money) { return false; } for (const auto& moneyEntry : moneyMap) { Item* item = moneyEntry.second; if (moneyEntry.first < money) { internalRemoveItem(item); money -= moneyEntry.first; } else if (moneyEntry.first > money) { const uint32_t worth = moneyEntry.first / item->getItemCount(); const uint32_t removeCount = (money / worth) + 1; addMoney(cylinder, (worth * removeCount) - money, flags); internalRemoveItem(item, removeCount); break; } else { internalRemoveItem(item); break; } } } else { int32_t value; player->getStorageValue(currencyId, value); if (value < money) { return false; } player->addStorageValue(currencyId, value - money); } return true; } Next find this
      void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) Replace the whole function with this
      void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/) { if (money == 0) { return; } if (Creature* creature = cylinder->getCreature()) { if (Player* player = creature->getPlayer()) { if(uint32_t currencyId = player->getNpcCurrencyId()){ int32_t value; player->getStorageValue(currencyId, value); player->addStorageValue(currencyId, value + money); return; } } } uint32_t crystalCoins = money / 10000; money -= crystalCoins * 10000; while (crystalCoins > 0) { const uint16_t count = std::min<uint32_t>(100, crystalCoins); Item* remaindItem = Item::CreateItem(ITEM_CRYSTAL_COIN, count); ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags); if (ret != RETURNVALUE_NOERROR) { internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); } crystalCoins -= count; } uint16_t platinumCoins = money / 100; if (platinumCoins != 0) { Item* remaindItem = Item::CreateItem(ITEM_PLATINUM_COIN, platinumCoins); ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags); if (ret != RETURNVALUE_NOERROR) { internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); } money -= platinumCoins * 100; } if (money != 0) { Item* remaindItem = Item::CreateItem(ITEM_GOLD_COIN, money); ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags); if (ret != RETURNVALUE_NOERROR) { internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT); } } }  
      npc.cpp
      Look for this
      pugi::xml_attribute attr; if ((attr = npcNode.attribute("speed"))) { baseSpeed = pugi::cast<uint32_t>(attr.value()); } else { baseSpeed = 100; } Right underneath that you are going to place this.
      if ((attr = npcNode.attribute("currency"))) { currency = pugi::cast<uint32_t>(attr.value()); }  
      npc.h
      Look for this
      bool isPushable() const final { return walkTicks > 0; } Place this right underneath
      uint32_t getCurrencyId() const { return currency; } Look for this
      uint32_t walkTicks; Place this right underneath
      uint32_t currency;  
      player.cpp
      Find this
      void Player::openShopWindow(Npc* npc, const std::list<ShopInfo>& shop) Replace that function with this
      void Player::openShopWindow(Npc* npc, const std::list<ShopInfo>& shop) { shopItemList = shop; sendShop(npc); sendSaleItemList(npc); } Next find this
      bool Player::updateSaleShopList(const Item* item) Replace that function with this
      bool Player::updateSaleShopList(const Item* item) { uint16_t itemId = item->getID(); if (itemId != ITEM_GOLD_COIN && itemId != ITEM_PLATINUM_COIN && itemId != ITEM_CRYSTAL_COIN) { auto it = std::find_if(shopItemList.begin(), shopItemList.end(), [itemId](const ShopInfo& shopInfo) { return shopInfo.itemId == itemId && shopInfo.sellPrice != 0; }); if (it == shopItemList.end()) { const Container* container = item->getContainer(); if (!container) { return false; } const auto& items = container->getItemList(); return std::any_of(items.begin(), items.end(), [this](const Item* containerItem) { return updateSaleShopList(containerItem); }); } } if (client) { client->sendSaleItemList(shopOwner, shopItemList); } return true; } Next you are going to look for
      uint64_t Player::getMoney() const Now right underneath that function you are going to place these.
      uint64_t Player::getMoney(Npc* npc) const { uint64_t cash; setNpcCurrencyId(npc); uint32_t currencyId = getNpcCurrencyId(); if (currencyId) { int32_t value; getStorageValue(currencyId, value); cash = (uint64_t)value; } else { cash = getMoney(); } return cash; } void Player::setNpcCurrencyId(Npc* npc) const{ currencyId = npc->getCurrencyId(); } uint32_t Player::getNpcCurrencyId() const { return currencyId; }  
      player.h
      Look for this
      uint64_t getMoney() const; Place this right underneath
      uint64_t getMoney(Npc*) const; void setNpcCurrencyId(Npc*) const; uint32_t getNpcCurrencyId() const; Find this
      void sendShop(Npc* npc) const { if (client) { client->sendShop(npc, shopItemList); } } Place this right underneath
      void sendSaleItemList(Npc* npc) const { if (client) { client->sendSaleItemList(npc, shopItemList); } } Find this
      uint32_t manaMax; Place this right underneath
      mutable uint32_t currencyId;  
      protocolgame.cpp
      Now find this function
      void ProtocolGame::sendSaleItemList(const std::list<ShopInfo>& shop) Place this right underneath
      void ProtocolGame::sendSaleItemList(Npc* npc, const std::list<ShopInfo>& shop) { NetworkMessage msg; msg.addByte(0x7B); msg.add<uint64_t>(player->getMoney(npc)); std::map<uint16_t, uint32_t> saleMap; if (shop.size() <= 5) { // For very small shops it's not worth it to create the complete map for (const ShopInfo& shopInfo : shop) { if (shopInfo.sellPrice == 0) { continue; } int8_t subtype = -1; const ItemType& itemType = Item::items[shopInfo.itemId]; if (itemType.hasSubType() && !itemType.stackable) { subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType); } uint32_t count = player->getItemTypeCount(shopInfo.itemId, subtype); if (count > 0) { saleMap[shopInfo.itemId] = count; } } } else { // Large shop, it's better to get a cached map of all item counts and use it // We need a temporary map since the finished map should only contain items // available in the shop std::map<uint32_t, uint32_t> tempSaleMap; player->getAllItemTypeCount(tempSaleMap); // We must still check manually for the special items that require subtype matches // (That is, fluids such as potions etc., actually these items are very few since // health potions now use their own ID) for (const ShopInfo& shopInfo : shop) { if (shopInfo.sellPrice == 0) { continue; } int8_t subtype = -1; const ItemType& itemType = Item::items[shopInfo.itemId]; if (itemType.hasSubType() && !itemType.stackable) { subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType); } if (subtype != -1) { uint32_t count; if (!itemType.isFluidContainer() && !itemType.isSplash()) { count = player->getItemTypeCount(shopInfo.itemId, subtype); // This shop item requires extra checks } else { count = subtype; } if (count > 0) { saleMap[shopInfo.itemId] = count; } } else { std::map<uint32_t, uint32_t>::const_iterator findIt = tempSaleMap.find(shopInfo.itemId); if (findIt != tempSaleMap.end() && findIt->second > 0) { saleMap[shopInfo.itemId] = findIt->second; } } } } uint8_t itemsToSend = std::min<size_t>(saleMap.size(), std::numeric_limits<uint8_t>::max()); msg.addByte(itemsToSend); uint8_t i = 0; for (std::map<uint16_t, uint32_t>::const_iterator it = saleMap.begin(); i < itemsToSend; ++it, ++i) { msg.addItemId(it->first); msg.addByte(std::min<uint32_t>(it->second, std::numeric_limits<uint8_t>::max())); } writeToOutputBuffer(msg); }  
      protocolgame.h
      Find this
      void sendSaleItemList(const std::list<ShopInfo>& shop); Place this right underneath
      void sendSaleItemList(Npc* npc, const std::list<ShopInfo>& shop);  
      luascript.cpp
      Find
      int LuaScriptInterface::luaPlayerAddMoney(lua_State* L) Replace that whole function with this
      int LuaScriptInterface::luaPlayerAddMoney(lua_State* L) { // player:addMoney(money[, currencyId]) uint64_t money = getNumber<uint64_t>(L, 2); uint32_t currencyId = getNumber<uint32_t>(L, 3); Player* player = getUserdata<Player>(L, 1); if (player) { if (currencyId) { int32_t value; player->getStorageValue(currencyId, value); player->addStorageValue(currencyId, value + money); } else { g_game.addMoney(player, money); } pushBoolean(L, true); } else { lua_pushnil(L); } return 1; } Next find this function which should be right below it.
      int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L) Replace that whole function with this
      int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L) { // player:removeMoney(money[, currencyId]) Player* player = getUserdata<Player>(L, 1); if (player) { uint64_t money = getNumber<uint64_t>(L, 2); uint32_t currencyId = getNumber<uint32_t>(L, 3); if (currencyId) { int32_t value; player->getStorageValue(currencyId, value); if (value < money) { pushBoolean(L, false); return 1; } player->addStorageValue(currencyId, value - money); pushBoolean(L, true); } else { pushBoolean(L, g_game.removeMoney(player, money)); } } else { lua_pushnil(L); } return 1; }  
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo