Ir para conteúdo
  • Cadastre-se

Posts Recomendados

Olá pessoal, preciso de ajuda... Em meu servidor eu tenho esse código que ao player chegar em tal nível ele ganha certa quantia em dinheiro...

 

Spoiler

function onAdvance(cid, skill, oldlevel, newlevel)

               if getPlayerLevel(cid) >= 8 and getPlayerStorageValue(cid, 99963) ~= 1 then
                            doPlayerSetBalance(cid, getPlayerBalance(cid) + 2000)
                            setPlayerStorageValue(cid, 99963, 1)
                            doPlayerSendTextMessage(cid, 19, "You have received 2000 gold in your bank for advancing to Level 8.")

            elseif getPlayerLevel(cid) >= 40 and getPlayerStorageValue(cid, 99964) ~= 1 then
                            doPlayerSetBalance(cid, getPlayerBalance(cid) + 10000)
                            setPlayerStorageValue(cid, 99964, 1)
                            doPlayerSendTextMessage(cid, 19, "You have received 10000 gold in your bank for advancing to Level 40.")

           elseif getPlayerLevel(cid) >= 50 and getPlayerStorageValue(cid, 99965) ~= 1 then
                            doPlayerSetBalance(cid, getPlayerBalance(cid) + 30000)
                            setPlayerStorageValue(cid, 99965, 1)
                            doPlayerSendTextMessage(cid, 19, "You have received 30000 gold in your bank for advancing to Level 50.")

             elseif getPlayerLevel(cid) >= 75 and getPlayerStorageValue(cid, 99966) ~= 1 then
                            doPlayerSetBalance(cid, getPlayerBalance(cid) + 60000)
                            setPlayerStorageValue(cid, 99966, 1)
                            doPlayerSendTextMessage(cid, 19, "You have received 60000 gold in your bank for advancing to Level 75.")
                
                                
            elseif getPlayerLevel(cid) >= 100 and getPlayerStorageValue(cid, 99969) ~= 1 then
                            doPlayerSetBalance(cid, getPlayerBalance(cid) + 100000)
                            setPlayerStorageValue(cid, 99969, 1)
                           doPlayerSendTextMessage(cid, 19, "You have received 10000 gold in your bank for advancing to Level 100.")
                            
                            
            
            elseif getPlayerLevel(cid) >= 150 and getPlayerStorageValue(cid, 99970) ~= 1 then
                            doPlayerAddItem(cid, 5942)
                            setPlayerStorageValue(cid, 99970, 1)
                            doPlayerSendTextMessage(cid, 19, "You have received one blessed wooden stake because you reached level 150.")

                    

 elseif getPlayerLevel(cid) >= 200 and getPlayerStorageValue(cid, 99971) ~= 1 then
                            doPlayerAddItem(cid, 2195)
                            setPlayerStorageValue(cid, 99971, 1)
                            doPlayerSendTextMessage(cid, 19, "You have been awarded with 1 boots of haste for reaching level 200.")

                                                
                            end
            return TRUE
end

 

Eu gostaria de mudar este código para o seguinte:

 

Nv. 20 ganhar Addon Citizen Full + 2 cristal coins

Nv. 50 ganhar montaria Donkey

Nv. 80 ganhar 1 Plague Mask (ID 13925) e um Plague Bell (ID 13926)

Nv. 100 ganhar Soft Boots (ID 6132)

Nv. 150 ganhar montaria Cristal Wolf

 

Obs. Se alguém puder entrar no servidor pra ver se consegue conectar eu ficaria muito grato, até agora não consegui ninguém pra testar ---> GranOT.tk

se quiser participar do desenvolvimento tem vaga rs' (principalmente se saber configurar o paypal do gesior...)

Link para o post
Compartilhar em outros sites

Este tópico foi movido para a área correta. Esta é uma mensagem automática!
Pedimos que leia as regras do fórum!

Spoiler

This topic has been moved to the correct area. This is an automated message!
Please read the forum rules.

 

 

 

 

Nós somos aquilo que fazemos repetidamente. Excelência, não é um modo de agir, mas um hábito.

                                                                                                                                                                                                                                        Aristóteles 

Link para o post
Compartilhar em outros sites

@Gabneitor tente utilizar a opção de storage pro addon montaria etc... na pasta xml e use o meu tópico de base pra editar o xml
obs: não é certeza que de pra fazer essa alteração no addon e monstaria nunca testei porém a lógica serve na outfit precisar de storage para liberar tente utilizar da mesma forma nos addons e montaria segue

obs: no caso é a opção de tag Quest="XXXX" no xml

 

Compre seus Scripts Agora totalmente seguro e de forma rápida, aceitamos também encomendas.

discord.gg/phJZeHa2k4

 

Projeto ATS (Naruto)

Informações Abaixo

Facebook

Youtube
Discord

 

Tutoriais / Conteúdos

Clique Aqui

Link para o post
Compartilhar em outros sites

  Bom esse codigo não e de autoria minha, mas e de um grande amigo acredito que ele não va ficar puto.

Apenas a parte de receber o addon foi eu que fiz mas esta funcional.

Codigo

Spoiler

 

Em CreatureScript.


<event type="advance" name="Recompense" script="others/recompense.lua"/>

Depois.


--Creditos @Marson


local table =
{	
	[20] = {type = "bank", id = 20000, msg = "You have received 20000 gold in your bank for advancing to Level 20."},
	
	[21] = {type = "outfit", addon_male = 128, addon_female =136, addon = 3, msg = "You have received Citizen Outfit full for advancing to Level 21."},	
	
	[50] = {type = "mount", id = 13, msg = "You have received a Donkey Mount for advancing to Level 50."},

	[80] = {type = "item", id = 13925, msg = "You have received one Plague Mask because you reached level 80."},
	
	[81] = {type = "item", id = 13926, msg = "You have been awarded with one Plague Bell for reaching level 81."},
	
	[100] = {type = "item", id = 6132, msg = "You have been awarded with one pair of Soft Boots for reaching level 100."},
	
	[150] = {type = "mount", id = 16, msg = "You have received a Crystal Wolf for advancing to Level 150."},
	

}

local storage = 99963

function onAdvance(player, skill, oldLevel, newLevel)

	if skill ~= SKILL_LEVEL or newLevel <= oldLevel then
		return true
	end

	for level, _ in pairs(table) do
		if newLevel >= level and player:getStorageValue(storage) < level then
			if table[level].type == "item" then
				player:addItem(table[level].id, 1)
				elseif table[level].type == "mount" then
				player:addMount(table[level].id)
			elseif table[level].type == "outfit" then
				doPlayerAddOutfit(player, table[level].addon_male, 3)
				doPlayerAddOutfit(player, table[level].addon_female, 3)
				doSendMagicEffect(getThingPos(player), 29)
			elseif table[level].type == "bank" then
				player:setBankBalance(player:getBankBalance() + table[level].id)
			else
				return false
			end

			player:sendTextMessage(MESSAGE_STATUS_CONSOLE_ORANGE, table[level].msg)
			player:setStorageValue(storage, level)
		end
	end

	player:save()

	return true
end


 

 

Os unicos bugs que sei que vai ter são, se por exemplo o maluco pular do level 8 para o 100 provavelmente so ira pegar uma recompensa.

E o outro é que não consegui entregar duas recompensas para o mesmo level.

De resto e isso espero que de boa ai. 

 

tibiaking.thumb.png.238aaedce11ce3d5e2cce5ff63229b06.png

Link para o post
Compartilhar em outros sites
3 horas atrás, sirarcken disse:

  Bom esse codigo não e de autoria minha, mas e de um grande amigo acredito que ele não va ficar puto.

Apenas a parte de receber o addon foi eu que fiz mas esta funcional.

Codigo

  Ocultar conteúdo

 

Em CreatureScript.



<event type="advance" name="Recompense" script="others/recompense.lua"/>

Depois.



--Creditos @Marson


local table =
{	
	[20] = {type = "bank", id = 20000, msg = "You have received 20000 gold in your bank for advancing to Level 20."},
	
	[21] = {type = "outfit", addon_male = 128, addon_female =136, addon = 3, msg = "You have received Citizen Outfit full for advancing to Level 21."},	
	
	[50] = {type = "mount", id = 13, msg = "You have received a Donkey Mount for advancing to Level 50."},

	[80] = {type = "item", id = 13925, msg = "You have received one Plague Mask because you reached level 80."},
	
	[81] = {type = "item", id = 13926, msg = "You have been awarded with one Plague Bell for reaching level 81."},
	
	[100] = {type = "item", id = 6132, msg = "You have been awarded with one pair of Soft Boots for reaching level 100."},
	
	[150] = {type = "mount", id = 16, msg = "You have received a Crystal Wolf for advancing to Level 150."},
	

}

local storage = 99963

function onAdvance(player, skill, oldLevel, newLevel)

	if skill ~= SKILL_LEVEL or newLevel <= oldLevel then
		return true
	end

	for level, _ in pairs(table) do
		if newLevel >= level and player:getStorageValue(storage) < level then
			if table[level].type == "item" then
				player:addItem(table[level].id, 1)
				elseif table[level].type == "mount" then
				player:addMount(table[level].id)
			elseif table[level].type == "outfit" then
				doPlayerAddOutfit(player, table[level].addon_male, 3)
				doPlayerAddOutfit(player, table[level].addon_female, 3)
				doSendMagicEffect(getThingPos(player), 29)
			elseif table[level].type == "bank" then
				player:setBankBalance(player:getBankBalance() + table[level].id)
			else
				return false
			end

			player:sendTextMessage(MESSAGE_STATUS_CONSOLE_ORANGE, table[level].msg)
			player:setStorageValue(storage, level)
		end
	end

	player:save()

	return true
end

 

 

 

 

 

Os unicos bugs que sei que vai ter são, se por exemplo o maluco pular do level 8 para o 100 provavelmente so ira pegar uma recompensa.

E o outro é que não consegui entregar duas recompensas para o mesmo level.

De resto e isso espero que de boa ai. 

 

tibiaking.thumb.png.238aaedce11ce3d5e2cce5ff63229b06.png

 

Mano funcionou aqui o script mais não ta aparecendo a mensagem para o player,

Chega no level e ele ganha o item normal. Da forma que ta ai ta tranquilo, não precisa ser os dois no mesmo level.

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 Imperius
      O propósito é criar uma nova função em creaturescripts que será acionada toda vez que um novo report (CTRL + R) for aberto.
       
      Eu implementei para enviar uma notificação no grupo do Telegram, contendo os dados do report.
       
      Isso garantirá que os GMs tenham acesso aos reports dos jogadores mesmo quando não estiverem logados, e também evitará que algum report seja perdido caso o jogador saia do servidor.
      A parte do Telegram é apenas um exemplo. Você pode ajustar o script para executar outras ações desejadas.
       
      creatureevent.cpp:
      Dentro deste arquivo, localize a função:
       
      uint32_t CreatureEvent::executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap)  
      abaixo dela, adicione:
       
      uint32_t CreatureEvent::executeOpenRuleViolation(Player* player, std::string message) { if (!m_interface->reserveEnv()) { std::clog << "[Error - CreatureEvent::executeOpenRuleViolation] Call stack overflow." << std::endl; return 0; } ScriptEnviroment* env = m_interface->getEnv(); env->setScriptId(m_scriptId, m_interface); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); lua_pushnumber(L, env->addThing(player)); lua_pushstring(L, message.c_str()); bool result = m_interface->callFunction(2); m_interface->releaseEnv(); return result; }  
      Após, procure por:
       
      std::string CreatureEvent::getScriptEventName() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "onLeaveChannel";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "onOpenRuleViolation";  
      Agora, procure por:
       
      std::string CreatureEvent::getScriptEventParams() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "cid, channel, users";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "cid, message";  
      Procure por:
       
      bool CreatureEvent::configureEvent(xmlNodePtr p)  
      abaixo de:
       
      else if(tmpStr == "leavechannel") m_type = CREATURE_EVENT_CHANNEL_LEAVE;  
      adicione:
       
      else if(tmpStr == "openruleviolation") m_type = CREATURE_EVENT_OPEN_RULE_VIOLATION;  
       
      creatureevent.h:
      Dentro deste arquivo, localize:
       
      enum CreatureEventType_t  
      adicione "CREATURE_EVENT_OPEN_RULE_VIOLATION" como o último item de enum CreatureEventType_t
       
      Exemplo:
       
      enum CreatureEventType_t { // ... CREATURE_EVENT_OPEN_RULE_VIOLATION };  
      Agora, procure por:
       
      uint32_t executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap);  
      abaixo dela, adicione:
       
      uint32_t executeOpenRuleViolation(Player* player, std::string message);  
      game.cpp:
      Dentro deste arquivo, localize:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text)  
      e substitua por:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text) { //Do not allow reports on multiclones worlds since reports are name-based if(g_config.getNumber(ConfigManager::ALLOW_CLONES)) { player->sendTextMessage(MSG_INFO_DESCR, "Rule violation reports are disabled."); return false; } cancelRuleViolation(player); boost::shared_ptr<RuleViolation> rvr(new RuleViolation(player, text, time(NULL))); ruleViolations[player->getID()] = rvr; ChatChannel* channel = g_chat.getChannelById(CHANNEL_RVR); if(!channel) return false; for(UsersMap::const_iterator it = channel->getUsers().begin(); it != channel->getUsers().end(); ++it) it->second->sendToChannel(player, SPEAK_RVR_CHANNEL, text, CHANNEL_RVR, rvr->time); CreatureEventList joinEvents = player->getCreatureEvents(CREATURE_EVENT_OPEN_RULE_VIOLATION); for(CreatureEventList::iterator it = joinEvents.begin(); it != joinEvents.end(); ++it) (*it)->executeOpenRuleViolation(player, text); return true; }  
      Agora é só compilar a source.
       
      depois em "data > creaturescripts > creaturescripts.xml", adicione:
       
      <event type="login" name="loginNotifyRuleViolation" script="notifyRuleViolation.lua"/> <event type="openruleviolation" name="openNotifyRuleViolation" script="notifyRuleViolation.lua"/>  
      em "data > creaturescripts > scripts", crie um arquivo notifyRuleViolation.lua e adicione:
       
      function onOpenRuleViolation(cid, message) local config = { token = "", -- Token do seu BOT no Telegram chatId = "" -- ID do chat do Telegram que será enviado a notificação. } local message = "Player: "..getCreatureName(cid).."\n\nReport:\n"..message.."" message = string.gsub(message, "\n", "%%0A") local url = "https://api.telegram.org/bot"..config.token.."/sendMessage" local data = "chat_id="..config.chatId.."&text="..message.."" local curl = io.popen('curl -d "'..data..'" "'..url..'"'):read("*a") return true end function onLogin(cid) registerCreatureEvent(cid, "openNotifyRuleViolation") return true end  
       
      Demonstração:
      1. Jogador abre um novo report (CTRL + R)

      2. notifyRuleViolation.lua, definido em creaturescripts.xml, é acionado para enviar uma notificação ao grupo do Telegram.
       

       
    • Por Ghaz
      Fala pessoal tudo bem?
       
      Estou com dificuldades em um script e preciso da ajuda dos magos do LUA rs.
       
      Tenho um script que quando o player morre (onDeath), ele faz algumas coisas e depois ele chama uma função que deveria retornar uma table (array) para eu fazer o for com o ipairs certinho. Segue abaixo o código:
       
       
      Segue abaixo a função getPlayersInArea:
       
       
      Acontece que no código de cima (do primeiro spoiler) eu dou um print no retorno da função getPlayersInArea, porém ela não tá me retornando a table, tá me retornando só: 2
       
       
       
      Alguém consegue me ajudar em, como raios eu faço a função retornar a lista de players ao invés da quantidade? Acredito que ta retornando o count da table, e não os itens do array.
       
       
      Agradeço desde já, valeu tchurma!
    • Por FeeTads
      salve rapaziada, estou fazendo uma quest no meu OT que é necessário faze-la durante 10 dias consecutivos, porém caso o player perca um dia, a storage da quest reseta.
      Já tenho esses scripts prontos de 2 formas: global event que checa a storage de todos os player online no momento e caso ja tenha passado 24h ele tira a storage do player que está entre os 10 dias de quest.
      E também tenho um creatureScript de onLogin() que quando o player loga, ele entra num loop de verificação a cada 60s

      minha duvida: globalEvents vai checar todos os players online de uma só vez e fazer as alterações necessarias, isso pode lagar a distro, ou até mesmo crashar?
      o creatureScript vai entrar num loop até o player deslogar, isso numa média de 250 pessoa são diversas verificações em momentos diferentes, pode acabar lagando ou crashando?

      meu OT possui uma media de 300 pessoas online.

      Script globalEvents é esse:

      function onThink(interval, lastExecution)
          local players = {}
          local timer = os.time()
          for _, pid in pairs (getPlayersOnline()) do
              local storage = getPlayerStorageValue(pid, 1231234)
              if getPlayerStorageValue(pid,888251) > 0 and getPlayerStorageValue(pid,888251) <= 9 then
                  if storage - timer <= 1  then
                      table.insert(players, pid)
                  end
              end
          end
          
          if #players > 0 then
              for i = 1, #players do
                  doPlayerSendTextMessage(players[i],22,"seu dano voltou ao normal por vc nao ter feito a quest!")
                  setPlayerStorageValue(players[i],888251,0)
              end
          end
      return true
      end

      Script do Creature é esse:
      local storage = getPlayerStorageValue(cid,1231234)
              function checkStorage(cid) local timer = os.time()
                     if not isPlayer(cid) then return true end
                     if getPlayerStorageValue(cid,888251) > 0 and getPlayerStorageValue(cid, 888251) <= 9 then
                             if storage - timer <= 1 then
                                     setPlayerStorageValue(cid,888251,0)
                             end
                   end
                   addEvent(function()
                              checkStorage(cid)
                    end, 60000)
      end
      function onLogin(cid)
              checkStorage(cid)
      return true
      end
      function onLogout(cid)
             stopEvent(checkStorage[cid])
      return true
      end


      caso os códigos nao estejam legiveis me avisem como arrumar em .lua pf

      se quiserem usar os códigos podem usar a vontade kkkkkkk
    • Por thelifeofpbion
      Existem alguns scripts que depois de matar boss abri tp para os players entrarem em uma sala de recompensa, porém (não sei se já existe) vou postar 2 scripts:

      1º Script: Todos players que der algum dano no boss é teleportado
      2º Script: Depois que o Boss for derrotado todos players de uma sala são teleportados.
       
       

       
      É Basicamente isso, tava ajudando no suporte quando pediram isso e resolvi postar para ficar mais facil de achar (e depois pra eu achar também).

      Agradeço o vodkart por ter disponibilizado a parte do script onde seleciona todos players de uma area (retirei de algum post do forum),
      e Xagah que copiei descaradamente as imagens de tópico porque achei bonito  

      Ajudei de alguma Forma? REP+.


       
    • Por Bruno Minervino
      Fala galera,
       
      Um membro fez um pedido, e achei que deveria compartilhar com vocês, algo simples porém útil. Principalmente em OT's do estilo Baiak.
       
      O que o script faz ?
      Ele simplesmente manda um efeito para o Top Level caso ele estiver online.
       
      Instalação:

      Em data/creaturescripts/creaturescripts.xml adicione:
      <event type="login" name="TopEffect" event="script" value="topeffect.lua"/> <event type="advance" name="CheckTop" event="script" value="topeffect.lua"/> Agora crie um arquivo em data/creaturescripts/scripts com o nome topeffect.lua e adicione:
      --[[ Script by Bruno Minervino para o Tibia King Caso for postar, colocar os créditos ]] local config = { tempo = 10, --tempo em segundos mensagem = { texto = "[TOP]", --não use mais de 9 caracteres efeito = TEXTCOLOR_LIGHTBLUE --efeito para a função doSendAnimatedText }, efeito = 30, --efeito da função doSendMagicEffect globalstr = 5687 -- uma global storage qualquer q esteje vazia } --[[ Não mexa em nada abaixo ]] local topPlayer = getGlobalStorageValue(config.globalstr) > 0 and getGlobalStorageValue(config.globalstr) or 0 function onLogin(cid) local query = db.getResult("SELECT `id`, `name`, `level` FROM `players` WHERE `group_id` < 2 ORDER BY `level` DESC LIMIT 1") if (query:getID() ~= -1) then local pid = query:getDataString("id") local name = query:getDataString("name") if getPlayerName(cid) == name then if topPlayer ~= getPlayerID(cid) then topPlayer = getPlayerID(cid) end setGlobalStorageValue(config.globalstr, pid) TopEffect(cid) end end registerCreatureEvent(cid, "CheckTop") return true end function onAdvance(cid, skill, oldlevel, newlevel) if skill == 8 then local query = db.getResult("SELECT `id`, `name`, `level` FROM `players` WHERE `group_id` < 2 ORDER BY `level` DESC LIMIT 1") if (query:getID() ~= -1) then local level = tonumber(query:getDataString("level")) if level < newlevel and topPlayer ~= getPlayerID(cid) then doBroadcastMessage("O jogador " .. getPlayerName(cid) .. " tornou-se o novo Top Level. Parabens!", 22) topPlayer = getPlayerID(cid) doSaveServer() setGlobalStorageValue(config.globalstr, getPlayerID(cid)) TopEffect(cid) end end end return true end function TopEffect(cid) if not isPlayer(cid) then return true end if topPlayer == getPlayerID(cid) then doSendAnimatedText(getCreaturePosition(cid), config.mensagem.texto, config.mensagem.efeito) doSendMagicEffect(getCreaturePosition(cid), config.efeito) addEvent(TopEffect, config.tempo * 1000, cid) end end function getPlayerNameById(id) local query = db.getResult("SELECT `name` FROM `players` WHERE `id` = " .. db.escapeString(id)) if query:getID() ~= -1 then return query:getDataString("name") end return 0 end function getPlayerIdByName(name) local query = db.getResult("SELECT `id` FROM `players` WHERE `name` = " .. db.escapeString(name)) if query:getID() ~= -1 then return tonumber(query:getDataString("id")) end return 0 end function getPlayerID(cid) return getPlayerIdByName(getPlayerName(cid)) end  
      Espero ajudar!
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo