Ir para conteúdo
  • Cadastre-se

Posts Recomendados

Olá pessoal, vi que muitos estavam tentando resolver o problema de um "CityWar Anti-Entrosa".de tal Empresa...

 

"O script só roda uma vez a  war e depois ele TRAVA, ."

Estava olhando o script aonde ocorria o problema e consegui resolver fiz vários testes e está rodando 100% sem erros! 

 

No arquivo tem o tutorial que ensina a instalar, se ajudei deixa um rep+

 

:)

 

File:Link

Scan: Link

 

 

-- EDIT---

Summon que matava os player na war fazia cair o servidor, agora está 100% estável o script.

 

Substituir o arquivo diretório talkactions/lib/war.lua 

@Way20 Créditos pela ajuda.

 



War = {
    
    numero = { 0, 10, 15, 20, 30, 40 },    -- quantidade de jogadores (0=infinito)
    tempo = { quinze_min = 15,          trinta_min = 30,            sessenta_min = 60 },            --    colocar o nome das variaveis iguais
    preco = { quinze_min = 75000,      trinta_min = 100000,     sessenta_min = 150000},        --  caso fizer alguma alteração
    
    modo = { tradicional = 1, semUe = 2, soSd = 3},
    modo_string = {
                    [1] = {'tradicional', 'padrao', 'normal', '1'},
                    [2] = {'sem ue', 'semue', 'semUe', '2'},
                    [3] = {'apenas sd', 'só sd', 'so sd' , 'soh sd', '3'}
    },    
    
    --[[        
            você pode colocar quantos mapas quiser de uma mesma cidade        
            na tabela referente ao mapa, cada vetor da matriz é composto da Posição do Time A e do B
            
            exemplo:            
            [0] = { {posA, posB}, {posA2, posB2}, {posA3, posA4}  }    -- aqui vc tem 3 mapas configurado para Edron
                        
            posA = local da cidade em que os jogadores da guild A será teleportados
            posB = local para a guild B
            
            você é livre para escolher quais e quantas copias da cidade
            
            preste atenção! o valor da string e da position deve ser o mesmo!
]]
    
    cidade_string = {
                          [0] = {'edron', "Edron", 'EDRON'},
                --[[      [1] = {'dara', 'darashia', 'Darashia', 'DARASHIA'},
                          [2] = {'lb', 'liberty bay', 'Liberty Bay', 'LIBERTY BAY'},
                          [3] = {'carlin', 'Carlin', 'CARLIN'},
                          [4] = {'cormaya', 'Cormaya', 'CORMAYA'},
                          [5] = {'ank', 'ankrahmun', 'Ankrahmun', 'ANKRAHMUN'},
                          [6] = {'yalahar', 'Yalahar', 'YALAHAR'},
                          [7] = {'venore', 'Venore', 'VENORE'}    ]]
    },
    mapas = {    
                          [0] = {     {{x=1178,y=636,z=7},{x=1178,y=692,z=7}}     },        -- exemplo de apenas um mapa Edron configurado
                          [1] = {},
                          [2] = {},
                          [3] = {},
                          [4] = {},
                          [5] = {},
                          [6] = {},
                          [7] = {}    
    },
}


for city, v in pairs(War.mapas) do
    for _, mapa in pairs(v) do
        Instances(city, mapa)
    end
end


Wars = {}

function War:new(id, param)
    
     return setmetatable({
     
            -- config
            id = id,
            desafiante = param.desafiante,
            aceito = false,
            numero_jogadores = param.numero,
            modo = param.modo,
            tempo = param.tempo,
            instanceid = param.instanceid,
            valor = param.valor,
            positions = {[param.guildA] = param.positionA, [param.guildB] = param.positionB},
            
            -- uso real
            players = {[param.guildA] = {}, [param.guildB] = {}},
            frags = {[param.guildA] = 0, [param.guildB] = 0},
            name = {}
            
            
     }, { __index = self }), addEvent(function (id, param) 
                                                    if Wars[id] and Wars[id].aceito == false then 
                                                        doPlayerDepositMoney(self.desafiante, valor)
                                                        Wars[id]:broadcastToGuilds(22, "O convite nao foi aceito.")
                                                        Wars[id] = false
                                                        Instances[param.instanceid]:unregister()
                                                    end
                                                end, 5 * 60 * 1000, id, param)
 end
 
setmetatable(Wars, { __call =     function(self, param) 
                                        local id = #Wars+1
                                        Instances[param.instanceid]:register()
                                        param.positionA = Instances[param.instanceid].posA
                                        param.positionB = Instances[param.instanceid].posB
                                        
                                        Wars[id] = War:new(id, param)
                                        
                                        Wars[id].name = {{param.guildA, param.nomeA}, {param.guildB, param.nomeB}}
                                        
                                        local text = "[City War] "..param.nomeA .. " invitou a guild " .. param.nomeB .. " para uma war!\n"
                                        text = text .. "A war sera na cidade " .. War.cidade_string[param.cidade][1]
                                        if (param.numero == 0) then                                        
                                            text = text .. " sem limite de jogadores para cada time"
                                        else
                                            text = text .. " com no maximo " .. param.numero .. " jogadores para cada time"
                                        end                                                                                
                                        text = text .. " por " .. param.tempo .. " minutos"
                                        text = text .. " no modo " .. War.modo_string[param.modo][1]
                                        text = text .. "\nO lider da guild " .. param.nomeB .. " tem cinco minutos para aceitar o convite. Digite: /citywar accept, " .. param.nomeA
                                        
                                        Wars[id]:broadcastToGuilds(22, text)
                                end })
                                                                
                                
function War:start()
    self.aceito = true    
    self:broadcastToGuilds(22, "[City War] A War entre " .. self.name[1][2] .. " e " .. self.name[2][2] .. "  foi iniciada! Para entrar digite: /citywar go" )
    
    addEvent(War.broadcast, (self.tempo * 60 * 1000) - (5 * 60 * 1000), self, 22, "[City War] Faltam 5 minutos para a War acabar.")
    addEvent(War.broadcast, (self.tempo * 60 * 1000) - (3 * 60 * 1000), self, 22, "[City War] Faltam 3 minutos para a War acabar.")
    addEvent(War.broadcast, (self.tempo * 60 * 1000) - (1 * 60 * 1000), self, 22, "[City War] Falta 1 minuto para a War acabar.")
    addEvent(War.finish, self.tempo * 60 * 1000, self)
end


function War:finish()
    
    local text = "A war entre as guilds " .. self.name[1][2] .. " e " .. self.name[2][2] .. " acabou!\n"
    text = text .. self:getPlacarString()
    self:broadcastToGuilds(22, text)
    
    for guild, teams in pairs(self.players) do
        for k, cid in pairs(teams) do
            if type(cid) == 'number' and isPlayer(cid) then
                local pos = getTownTemplePosition(getPlayerTown(cid))            
                doTeleportThing(cid, pos)            
                
                setPlayerWarType(cid, 0)
                unregisterCreatureEvent(cid, "morte")    
                
                doRemoveCondition(cid, CONDITION_INFIGHT)
                if getCreatureSkullType(cid) == SKULL_WHITE then
                    doCreatureSetSkullType(cid, 0)
                end
                
                self.players[guild][k] = nil
            end
        end
    end    
    Instances[self.instanceid]:unregister()
    
    db.executeQuery("INSERT INTO `city_war` (`frags_guild1`, `frags_guild2`, `guild1`, `guild2`, `tempo`, `modo`) VALUES ('" .. self.frags[self.name[1][1]] .. "', '" .. self.frags[self.name[2][1]] .. "', '" .. self.name[1][2] .. "', '" .. self.name[2][2] .. "', '" .. self.tempo .. "', '" .. self.modo .. "' );")
    Wars[self.id] = true
end


local condition_infight = createConditionObject(CONDITION_INFIGHT, -1)

function War:newPlayer(cid)
    if self.aceito == false then
        doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "The war was not accepted yet.")
        return true
    end


    local guildId = getPlayerGuildId(cid)
        if (self.numero_jogadores == 0 or table.elements(self.players[guildId]) < self.numero_jogadores) then
            doTeleportThing(cid, self.positions[guildId])
            table.insert(self.players[guildId], cid)
        else
            return false
        end
    doAddCondition(cid, condition_infight)
    setPlayerWarType(cid, self.modo)
    registerCreatureEvent(cid, "citywar")
    return true
end


function War:removePlayer(cid)
    --town = getPlayerTown(cid)
    --pos = getTownTemplePosition(town)        
            
    --doTeleportThing(cid, pos)
    
    setPlayerWarType(cid, 0)    
    unregisterCreatureEvent(cid, "citywar")


    tmp = false
    for guild, teams in pairs(self.players) do
        for k, v in pairs(teams) do
            if v == cid then
                self.players[guild][k] = nil
                tmp = true
                break
            end
        end
        if tmp == true then
            break
        end
    end
    doRemoveCondition(cid, CONDITION_INFIGHT)
    if getCreatureSkullType(cid) == SKULL_WHITE then
        doCreatureSetSkullType(cid, 0)
    end
end


function War:isGuildOnWar(guildId)
    if self.name[1][1] == guildId or self.name[2][1] == guildId then
        return true    
    end
        return false
end


function War:kill(killer, cid)
    if (isPlayer(killer) or (isMonster(killer) and getCreatureMaster(killer))) then
        killer = isPlayer(killer) and killer or getCreatureMaster(killer)
        if getPlayerGuildId(killer) ~= getPlayerGuildId(cid) then
            self.frags[getPlayerGuildId(killer)] = self.frags[getPlayerGuildId(killer)] + 1
            self:broadcast(22, "[City War] \n".. getPlayerName(killer) .. " matou " .. getPlayerName(cid) .. ".\n" .. self:getPlacarString())
        end
    end
end


function War:getPlacarString()
    local text = "Placar: " .. self.name[1][2] .. " " .. self.frags[self.name[1][1]] .. " x "
    text = text .. self.frags[self.name[2][1]] .. " " .. self.name[2][2].."."    
    return text
end


function War:broadcast(messagetype, text)
    for k, v in pairs(self.players) do
        for _, cid in pairs(v) do
            if isPlayer(cid) then
                doPlayerSendTextMessage(cid, messagetype, text)
            end
        end
    end
end


function War:broadcastToGuilds(messagetype, text)
    local guilds = {self.name[1][1], self.name[2][1]}
    local isinarray, sendmessage, getguildid = isInArray, doPlayerSendTextMessage, getPlayerGuildId
    
    for k, v in pairs(getPlayersOnline()) do
        if isinarray(guilds, getguildid(v)) then
            sendmessage(v, messagetype, text)
        end
    end
end


-- função static, callback entre creaturescripts e o evento
function War.morte(cid, killer)
    for k,v in pairs(Wars) do
        if type(v) == 'table' then
            if v:isGuildOnWar(getPlayerGuildId(cid)) then
                v:kill(killer, cid)
                v:removePlayer(cid)
            end
        end
    end
    return true
end


Editado por maleskinho (veja o histórico de edições)
Link para o post
Compartilhar em outros sites
  • 4 weeks later...

da erro na hora de compilar. aqui nao funcionou.

 

In file included from spells.h:28:0,
                 from actions.cpp:35:
talkaction.h:63:25: error: ‘virtual LuaInterface& TalkActions::getInterface()’ cannot be overloaded
   virtual LuaInterface& getInterface() {return m_interface;}
                         ^
talkaction.h:61:25: error: with ‘virtual LuaInterface& TalkActions::getInterface()’
   virtual LuaInterface& getInterface() {return m_interface;}
                         ^
talkaction.h:64:16: error: redeclaration of ‘LuaInterface TalkActions::m_interface’
   LuaInterface m_interface;
                ^
talkaction.h:62:16: note: previous declaration ‘LuaInterface TalkActions::m_interface’
   LuaInterface m_interface;
 

Editado por lorinhu99 (veja o histórico de edições)
Link para o post
Compartilhar em outros sites
  • 2 weeks later...
Em 04/05/2018 em 15:06, lorinhu99 disse:

da erro na hora de compilar. aqui nao funcionou.

 

In file included from spells.h:28:0,
                 from actions.cpp:35:
talkaction.h:63:25: error: ‘virtual LuaInterface& TalkActions::getInterface()’ cannot be overloaded
   virtual LuaInterface& getInterface() {return m_interface;}
                         ^
talkaction.h:61:25: error: with ‘virtual LuaInterface& TalkActions::getInterface()’
   virtual LuaInterface& getInterface() {return m_interface;}
                         ^
talkaction.h:64:16: error: redeclaration of ‘LuaInterface TalkActions::m_interface’
   LuaInterface m_interface;
                ^
talkaction.h:62:16: note: previous declaration ‘LuaInterface TalkActions::m_interface’
   LuaInterface m_interface;
 

Que distro é? testei na OTX..

Link para o post
Compartilhar em outros sites
  • 2 months later...

@maleskinho

 

Poderia arrumar para mim? não consigo.

 

Talkaction.h

////////////////////////////////////////////////////////////////////////
// OpenTibia - an opensource roleplaying game
////////////////////////////////////////////////////////////////////////
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
////////////////////////////////////////////////////////////////////////

#ifndef __TALKACTION__
#define __TALKACTION__
#include "otsystem.h"

#include "enums.h"
#include "player.h"

#include "tools.h"
#include "luascript.h"
#include "baseevents.h"

enum TalkActionFilter
{
	TALKFILTER_QUOTATION,
	TALKFILTER_WORD,
	TALKFILTER_WORD_SPACED,
	TALKFILTER_LAST
};

class TalkAction;
typedef std::map<std::string, TalkAction*> TalkActionsMap;

class TalkActions : public BaseEvents
{
	public:
		TalkActions();
		virtual ~TalkActions();

		bool onPlayerSay(Creature* creature, uint16_t channelId, const std::string& words, bool ignoreAccess);

		inline TalkActionsMap::const_iterator getFirstTalk() const {return talksMap.begin();}
		inline TalkActionsMap::const_iterator getLastTalk() const {return talksMap.end();}

	protected:
		TalkAction* defaultTalkAction;
		TalkActionsMap talksMap;

		virtual std::string getScriptBaseName() const {return "talkactions";}
		virtual void clear();

		virtual Event* getEvent(const std::string& nodeName);
		virtual bool registerEvent(Event* event, xmlNodePtr p, bool override);

		virtual LuaInterface& getInterface() {return m_interface;}
		LuaInterface m_interface;
};

typedef bool (TalkFunction)(Creature* creature, const std::string& words, const std::string& param);
class TalkAction : public Event
{
	public:
		TalkAction(const TalkAction* copy);
		TalkAction(LuaInterface* _interface);
		virtual ~TalkAction() {}

		virtual bool configureEvent(xmlNodePtr p);
		virtual bool loadFunction(const std::string& functionName);

		int32_t executeSay(Creature* creature, const std::string& words, std::string param, uint16_t channel);

		std::string getFunctionName() const {return m_functionName;}
		std::string getWords() const {return m_words;}
		void setWords(const std::string& words) {m_words = words;}

		TalkActionFilter getFilter() const {return m_filter;}
		uint32_t getAccess() const {return m_access;}
		int32_t getChannel() const {return m_channel;}

		StringVec getExceptions() {return m_exceptions;}
		TalkFunction* getFunction() {return m_function;}

		bool isLogged() const {return m_logged;}
		bool isHidden() const {return m_hidden;}
		bool isSensitive() const {return m_sensitive;}

		bool hasGroups() const {return !m_groups.empty();}
		bool hasGroup(int32_t value) const {return std::find(m_groups.begin(), m_groups.end(), value) != m_groups.end();}

		IntegerVec::const_iterator getGroupsBegin() const {return m_groups.begin();}
		IntegerVec::const_iterator getGroupsEnd() const {return m_groups.end();}

	protected:
		virtual std::string getScriptEventName() const {return "onSay";}
		virtual std::string getScriptEventParams() const {return "cid, words, param, channel";}

		static TalkFunction houseBuy;
		static TalkFunction houseSell;
		static TalkFunction houseKick;
		static TalkFunction houseDoorList;
		static TalkFunction houseGuestList;
		static TalkFunction houseSubOwnerList;
		static TalkFunction guildJoin;
		static TalkFunction guildCreate;
		static TalkFunction thingProporties;
		static TalkFunction banishmentInfo;
		static TalkFunction diagnostics;
		static TalkFunction ghost;
		static TalkFunction software;

		std::string m_words, m_functionName;
		TalkFunction* m_function;
		TalkActionFilter m_filter;
		uint32_t m_access;
		int32_t m_channel;
		bool m_logged, m_hidden, m_sensitive;
		StringVec m_exceptions;
		IntegerVec m_groups;
};
#endif

luascript.cpp

https://pastebin.com/KVKitnRV

Link para o post
Compartilhar em outros sites
  • 2 weeks later...
  • 2 months later...
  • 3 weeks later...
  • 7 months later...
  • 10 months later...
Em 17/07/2019 em 18:48, mattos123 disse:

tava testando aqui, ele crasha o server, quando player ta com guildwar ativo, e em party, alguem tem relatos sobre tal ?

OMG i will check this.

 

command /citywar exit   no run  the player no leave to the city but the storage disappears and when his die the count kill no take can help me please?

Link para o post
Compartilhar em outros sites
  • 2 weeks later...

Olá, fiz a instalação noo meu servidor, porém ele não está inserindo as informações na database

e quando mata o jogador não contabiliza. Se alguém souber como resolver. Agradeç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 Fausto32
      Script/Tutorial+ Php +Map +Talkaction +Portal.
      Ps: Antes de falar q o topico já existe no forum teste os outros scripts
      Então começando por informações basícas :
      Para abrir o evento : /zombiestart numero de players . exemplo : /zombiestart 2
      Para Iniciar o evento sem o numero maximo de players: /zombiestart force.
      Apos aberto sempre q um player ente no portal do evento e avisado por broadcast quem
      entrou na arena e o numero de players restantes para o evento ser iniciado.
      Apos o evento ser iniciado um zombie e sumonado a cada 20 segundos, o player que for infectado e teleportado para o templo vence o ultimo player restante na arena.
      Ao terminar o evento e anuciado por broadcast o nome do player vencedor tempo q durou na arena e por quantos zombies ele sobreviveu, entrega de premio automatica, premio configuravel.
      Garantia de funcionabilidade perfeita em TFS 0.4 se configurado corretamente, não testado em outras versões de distros.
      Creditos: Me .. não criei mais montei peguei de varios servers/topicos e corigi os varios bugs de distro colocaria os creditos de onde peguei a maioria do script mais foi de um server sem creditos q nem era pra ter sido postado.
      Enfim Vamos ao Evento !
      Primeiro vou estar postando a pagina classica do Zombie event no Gesior que seria a parte PHP para informar os players sobre o evento.
      Pagina PHP + Tutorial de como implementar ela no seu site.
      Agora alguns mapas para o zombie event:
      Então Agora vamos ao script !
      data\creaturescripts\scripts\zombie – A pasta ‘zombie’ deve ser criada no diretorio citado.
      \data\creaturescripts\scripts\Zombie\onattack.lua
        function loseOnZombieArena(cid) kickPlayerFromZombiesArea(cid) doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "BOOM! You are dead.") local players = getZombiesEventPlayers() if(#players <= 1) then local winner = players[1] if(winner) then doPlayerAddItem(winner, 2157, 5, true) doPlayerAddItem(winner, 6119, 1, true) doPlayerSendTextMessage(winner, MESSAGE_STATUS_CONSOLE_BLUE, "You won zombies arena event.") doBroadcastMessage("After " .. os.time() - getPlayerZombiesEventStatus(winner) .. " seconds of fight " .. getCreatureName(winner) .. " won Zombie Arena Event in game versus " .. getStorage(ZE_ZOMBIES_SPAWNED) .. " zombies!") kickPlayerFromZombiesArea(winner) else doBroadcastMessage("Zombie arena event finished! No one win?!?!?! WTF!") end doSetStorage(ZE_STATUS, 0) doSetStorage(ZE_PLAYERS_NUMBER, ZE_DEFAULT_NUMBER_OF_PLAYERS) doSetStorage(ZE_ZOMBIES_TO_SPAWN, 0) doSetStorage(ZE_ZOMBIES_SPAWNED, 0) local width = (math.max(ZE_spawnFromPosition.x, ZE_spawnToPosition.x) - math.min(ZE_spawnFromPosition.x, ZE_spawnToPosition.x)) / 2 + 1 local height = (math.max(ZE_spawnFromPosition.y, ZE_spawnToPosition.y) - math.min(ZE_spawnFromPosition.y, ZE_spawnToPosition.y)) / 2 + 1 local centerPos = {x=math.min(ZE_spawnFromPosition.x, ZE_spawnToPosition.x)+width,y=math.min(ZE_spawnFromPosition.y, ZE_spawnToPosition.y)+height,z=ZE_spawnFromPosition.z} for z = math.min(ZE_spawnFromPosition.z, ZE_spawnToPosition.z), math.max(ZE_spawnFromPosition.z, ZE_spawnToPosition.z) do centerPos.z = z for i, uid in pairs(getSpectators(centerPos, width, height, false)) do if(isMonster(uid)) then doRemoveCreature(uid) end end end end end function onStatsChange(target, cid, changetype, combat, value) if((cid and isMonster(cid) and getCreatureName(cid) == "Zombie Event") or (isInRange(getThingPosition(target), ZE_spawnFromPosition, ZE_spawnToPosition) and changetype == STATSCHANGE_HEALTHLOSS and math.abs(value) >= getCreatureHealth(target))) then doCreatureAddHealth(target, getCreatureMaxHealth(target)) loseOnZombieArena(target) return false end return true end \data\creaturescripts\scripts\Zombie\ondeath.lua
        function onDeath(cid) setZombiesToSpawnCount(getZombiesToSpawnCount() + 2) doCreatureSay(cid, "I'll be back!", 19) return true end \data\creaturescripts\scripts\Zombie\onthink.lua
        function onThink(cid) local target = getCreatureTarget(cid) if(target ~= 0 and not isPlayer(target)) then doRemoveCreature(target) end return true end \data\globalevents\scripts\zombie\ onstartup.lua
        function onstartup() db.executeQuery("UPDATE `player_storage` SET `value` = 0 WHERE `key` = " .. ZE_isOnZombieArea .. ";") doSetStorage(ZE_STATUS, 0) doSetStorage(ZE_PLAYERS_NUMBER, ZE_DEFAULT_NUMBER_OF_PLAYERS) doSetStorage(ZE_ZOMBIES_TO_SPAWN, 0) doSetStorage(ZE_ZOMBIES_SPAWNED, 0) addZombiesEventBlockEnterPosition() return true end \data\globalevents\scripts\zombie\onthink.lua
        function onThink(interval, lastExecution, thinkInterval) if(getStorage(ZE_STATUS) == 2) then setZombiesToSpawnCount(getZombiesToSpawnCount()+1) local players = getZombiesEventPlayers() for i=1, getZombiesToSpawnCount() * 2 do if(getZombiesToSpawnCount() > 0 and spawnNewZombie()) then setZombiesToSpawnCount(getZombiesToSpawnCount()-1) end end end return true end \data\lib\zombie_event.lua
        -- CONFIG ZE_DEFAULT_NUMBER_OF_PLAYERS = 20 ZE_ACCESS_TO_IGNORE_ARENA = 4 -- POSITIONS ZE_blockEnterItemPosition = {x=32341, y=32213, z=7} -- onde nasce o teleport? ZE_enterPosition = {x=32154, y=32578, z=7} -- onde os players nascem dentro da arena zombie? ZE_kickPosition = {x=32368, y=32241, z=7} -- quando morre vai para onde? ZE_spawnFromPosition = {x=32140,y=32566,z=7} -- para sumonar zombie (de) ZE_spawnToPosition = {x=32168,y=32590,z=7} -- para sumonar zombie (ate) -- ITEM IDS --ZE_blockEnterItemID = 2700 ZE_blockEnterItemID = 1387 -- STORAGES -- - player ZE_isOnZombieArea = 34370 -- - global ZE_STATUS = 34370 -- =< 0 - off, 1 - waiting for players, 2 - is running ZE_PLAYERS_NUMBER = 34371 ZE_ZOMBIES_TO_SPAWN = 34372 ZE_ZOMBIES_SPAWNED = 34373 -- FUNCTION function setZombiesEventPlayersLimit(value) doSetStorage(ZE_PLAYERS_NUMBER, value) end function getZombiesEventPlayersLimit() return getStorage(ZE_PLAYERS_NUMBER) end function addPlayerToZombiesArea(cid) doSendMagicEffect(getThingPosition(cid), CONST_ME_TELEPORT) doTeleportThing(cid, ZE_enterPosition, true) doSendMagicEffect(getThingPosition(cid), CONST_ME_TELEPORT) if(getPlayerAccess(cid) < ZE_ACCESS_TO_IGNORE_ARENA) then setPlayerZombiesEventStatus(cid, os.time()) end end function kickPlayerFromZombiesArea(cid) doSendMagicEffect(getThingPosition(cid), CONST_ME_TELEPORT) doTeleportThing(cid, ZE_kickPosition, true) doSendMagicEffect(getThingPosition(cid), CONST_ME_TELEPORT) setPlayerZombiesEventStatus(cid, 0) end function getPlayerZombiesEventStatus(cid) return getCreatureStorage(cid, ZE_isOnZombieArea) end function setPlayerZombiesEventStatus(cid, value) doCreatureSetStorage(cid, ZE_isOnZombieArea, value) end function getZombiesEventPlayers() local players = {} for i, cid in pairs(getPlayersOnline()) do if(getPlayerZombiesEventStatus(cid) > 0) then table.insert(players, cid) end end return players end function getZombiesCount() return getStorage(ZE_ZOMBIES_SPAWNED) end function addZombiesCount() doSetStorage(ZE_ZOMBIES_SPAWNED, getStorage(ZE_ZOMBIES_SPAWNED)+1) end function resetZombiesCount() doSetStorage(ZE_ZOMBIES_SPAWNED, 0) end function getZombiesToSpawnCount() return getStorage(ZE_ZOMBIES_TO_SPAWN) end function setZombiesToSpawnCount(count) doSetStorage(ZE_ZOMBIES_TO_SPAWN, count) end function addZombiesEventBlockEnterPosition() -- remove tp -- remove o TP local item = getTileItemById(ZE_blockEnterItemPosition, ZE_blockEnterItemID) if(item.uid ~= 0) then doRemoveItem(item.uid) end --doRemoveItem(getThingFromPos(Castle.desde).uid) --[[ if(getTileItemById(ZE_blockEnterItemPosition, ZE_blockEnterItemID).uid == 0) then doCreateItem(ZE_blockEnterItemID, 1, ZE_blockEnterItemPosition) end ]]-- end function removeZombiesEventBlockEnterPosition() -- add tp if(getTileItemById(ZE_blockEnterItemPosition, ZE_blockEnterItemID).uid == 0) then --doCreateItem(ZE_blockEnterItemID, 1, ZE_blockEnterItemPosition) local tp = doCreateTeleport(ZE_blockEnterItemID, ZE_enterPosition, ZE_blockEnterItemPosition) doItemSetAttribute(tp, "aid", "5555") end --[[ local item = getTileItemById(ZE_blockEnterItemPosition, ZE_blockEnterItemID) if(item.uid ~= 0) then doRemoveItem(item.uid) end ]]-- end function spawnNewZombie() local posx = {} local posy = {} local posz = {} local pir = {} for i=1, 5 do local posx_tmp = math.random(ZE_spawnFromPosition.x ,ZE_spawnToPosition.x) local posy_tmp = math.random(ZE_spawnFromPosition.y ,ZE_spawnToPosition.y) local posz_tmp = math.random(ZE_spawnFromPosition.z ,ZE_spawnToPosition.z) local pir_tmp = 0 local spec = getSpectators({x=posx_tmp, y=posy_tmp, z=posz_tmp}, 3, 3, false) if(spec and #spec > 0) then for z, pid in pairs(spec) do if(isPlayer(pid)) then pir_tmp = pir_tmp + 1 end end end posx[i] = posx_tmp posy[i] = posy_tmp posz[i] = posz_tmp pir[i] = pir_tmp end local lowest_i = 1 for i=2, 5 do if(pir[i] < pir[lowest_i]) then lowest_i = i end end local ret = doCreateMonster("Zombie Event", {x=posx[lowest_i], y=posy[lowest_i], z=posz[lowest_i]}, false) if type(ret) == "number" then addZombiesCount() setGlobalStorageValue(201201051801, ret) end return type(ret) == "number" end \data\movements\scripts\zombie\ onenter.lua
        function onStepIn(cid, item, position, lastPosition, fromPosition, toPosition, actor) if(not isPlayer(cid)) then return true end if(getPlayerAccess(cid) >= ZE_ACCESS_TO_IGNORE_ARENA) then addPlayerToZombiesArea(cid) elseif(#getZombiesEventPlayers() < getZombiesEventPlayersLimit() and getStorage(ZE_STATUS) == 1) then addPlayerToZombiesArea(cid) local players_on_arena_count = #getZombiesEventPlayers() if(players_on_arena_count == getZombiesEventPlayersLimit()) then addZombiesEventBlockEnterPosition() -- removeTP doSetStorage(ZE_STATUS, 2) doBroadcastMessage("Zombie Arena Event started.") else doBroadcastMessage(getCreatureName(cid) .. " has entered a Zombie Arena. We still need " .. getZombiesEventPlayersLimit() - players_on_arena_count .. " players.") end else doTeleportThing(cid, fromPosition, true) addZombiesEventBlockEnterPosition() end return true end \data\talkactions\scripts\zombie\ onsay.lua
        function onSay(cid, words, param, channel) if(getStorage(ZE_STATUS) ~= 2) then local players_on_arena_count = #getZombiesEventPlayers() if(param == 'force') then if(players_on_arena_count > 0) then setZombiesEventPlayersLimit(players_on_arena_count ) addZombiesEventBlockEnterPosition() doSetStorage(ZE_STATUS, 2) doBroadcastMessage("Zombie Arena Event started.") doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Zombies event started.") else doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Cannot start Zombies event. There is no players on arena.") end else if(param ~= '' and tonumber(param) > 0) then setZombiesEventPlayersLimit(tonumber(param)) end removeZombiesEventBlockEnterPosition() doSetStorage(ZE_STATUS, 1) doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Event started.") doPlayerBroadcastMessage(cid, "Zombie Arena Event teleport is opened. We are waiting for " .. getZombiesEventPlayersLimit() - players_on_arena_count .. " players to start.") end else doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Zombies event is already running.") end return true end data\monster\zombie_event.xml
        <monster name="Zombie Event" nameDescription="an event zombie" race="undead" experience="480" speed="170" manacost="0"> <health now="20000" max="20000"/> <look type="311" corpse="9875"/> <targetchange interval="5000" chance="50"/> <strategy attack="100" defense="0"/> <flags> <flag summonable="0"/> <flag attackable="1"/> <flag hostile="1"/> <flag illusionable="0"/> <flag convinceable="0"/> <flag pushable="0"/> <flag canpushitems="1"/> <flag canpushcreatures="1"/> <flag targetdistance="1"/> <flag staticattack="90"/> <flag runonhealth="0"/> </flags> <attacks> <attack name="melee" interval="1000" min="-1500" max="-2350"/> </attacks> <defenses armor="0" defense="0"/> <immunities> <immunity paralyze="1"/> <immunity invisible="1"/> <immunity fire="1"/> <immunity energy="1"/> <immunity poison="1"/> </immunities> <voices interval="5000" chance="10"> <voice sentence="You wont last long!"/> <voice sentence="Mmmmh.. braains!"/> </voices> <script> <event name="ZombieThink"/> <event name="ZombieDeath"/> </script> <loot> </loot> </monster> Agora as Tags nos xml’s . /data/creaturescripts/creaturescripts.xml
        <event type="think" name="ZombieThink" event="script" value="zombie/onthink.lua"/> <event type="statschange" name="ZombieAttack" event="script" value="zombie/onattack.lua"/> <event type="death" name="ZombieDeath" event="script" value="zombie/ondeath.lua"/> /data/globalevents/globalevents.xml
        <globalevent name="ZombieGlobalThink" interval="5000" event="script" value="zombie/onthink.lua"/> <globalevent name="ZombieGlobalStartup" type="start" event="script" value="zombie/onstartup.lua"/> /data/movements/movements.xml
        <movevent type="StepIn" actionid="5555" event="script" value="zombie/onenter.lua"/> /data/talkactions/talkactions.xml
        <talkaction log="yes" words="/zombiestart" access="4" event="script" value="zombie/onsay.lua"/> /data/monster/monsters.xml
        <monster name="Zombie Event" file="zombie_event.xml"/> Script Terminado ! Next: Tutorial de como configurar o zombie event ! Estarei postando apenas as partes q podem ou devem ser editadas em cada script. data\creaturescripts\scripts\zombiez\onattack.lua
      Next: \data\lib\zombie_event.lua
      Então galera eh isso ai .-. meu primeiro post não mim crucifiquem k Duvidas, reclamações elogios chigamentos u.u só comentar como dizia o mestre o topico ta explicado nos minimos detalhes e ''de forma bem entendida'' (entendedoresentenderam) então eh isso vlw ai a todos q mim ajudaram nisso e nem sabem ?
    • Por Garou
      ADVANCED FORGE SYSTEM
      O SISTEMA DE CRIAÇÃO DE ITENS PARA SEU SERVIDOR
       
      Creio que muitos já conhecem o sistema de forja criado por mim, acontece que o código já estava um pouco obsoleto, então resolvi reescrever ele do 0.
      Simplesmente consiste em um sistema de criação de itens avançado que ressuscita um pouco do RPG perdido nos servidores de hoje em dia. O jogador poderá criar itens através de forja, agindo como um verdadeiro ferreiro medieval. Adiciona itens em cima de uma bigorna previamente colocada no mapa e com um martelo cria um item totalmente novo.
      CARACTERÍSTICAS DA VERSÃO FINAL:
      - Configuração intuitiva e fácil de compreender;
      - Mini-tutorial auxiliando criação de novas receitas;
      - Receitas podem conter até 250 itens diferentes com suas respectivas quantidades;
      - Sistema inteligente que identifica uma receita em qualquer ordem;
      - Código totalmente orientado a objetos;
      - Possibilidade de configurar diferentes requerimentos, diferentes skills, magic level e level
       
      Há dois modos de instalar o Advanced Forge System, o primeiro é seguir os passos deste tópico e o segundo e baixar pasta data/ anexada no tópico com os arquivos em seus respectivos diretórios, precisando apenas o registro das chaves nos arquivos XML.
      Escolha o modo que mais convém a você.
       
      Crie um arquivo em data/lib chamado forgesystem.lua e cole o conteúdo abaixo:
        --[[ ADVANCED FORGE SYSTEM FINAL Criado por Oneshot É proibido a venda ou a cópia sem os devidos créditos desse script. ]]-- RecipeHandler = { itemtype = 0, items = {}, level = 1, maglevel = 0, skills = {[0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0, [6] = 0} } Forge = { type = nil, position = nil, magicEffect = CONST_ME_MAGIC_GREEN, messages = { class = MESSAGE_STATUS_DEFAULT, success = "You have successfully forged a %s.", needskill = "You don't have enough %s to create a %s.", needlevel = "You need level %s to create a %s.", needmaglevel = "You need magic level %s to create a %s." } } function RecipeHandler:new(itemtype, items, level, maglevel, skills) local obj = { itemtype = (itemtype or 0), items = (items or {}), level = (level or 1), maglevel = (maglevel or 0), skills = (skills or {[0] = 0, [1] = 0, [2] = 0, [3] = 0, [4] = 0, [5] = 0, [6] = 0}) } table.insert(Recipes, obj) return setmetatable(obj, {__index = self}) end function RecipeHandler:setItem(itemtype) self.itemtype = (itemtype or 0) end function RecipeHandler:setRecipe(...) self.items = {...} end function RecipeHandler:setRecipeItem(itemid, amount) table.insert(self.items, {itemid, amount}) end function RecipeHandler:setSkill(skillid, value) self.skills[skillid] = value end function RecipeHandler:setLevel(value) self.level = value end function RecipeHandler:setMagLevel(value) self.maglevel = value end function RecipeHandler:check(position) local match = false for n, item in ipairs(self.items) do local thing = getTileItemById(position, item[1]) if thing.uid > 0 and math.max(1, thing.type) >= item[2] then if n == #self.items then match = true end else break end end return match end function RecipeHandler:get(position) if self:check(position) == true then return setmetatable({type = self, position = position}, {__index = Forge}) end return false end function Forge:create(cid) if self.type.itemid == 0 then print("[FORGE SYSTEM - ERROR] ATTEMPT TO CREATE A RECIPE ITEMID 0") return end local status = true if(cid) then if getPlayerLevel(cid) < self.type.level then doPlayerSendTextMessage(cid, self.messages.class, self.messages.needlevel:format(self.type.level, getItemNameById(self.type.itemtype))) return end if getPlayerMagLevel(cid) < self.type.maglevel then doPlayerSendTextMessage(cid, self.messages.class, self.messages.needmaglevel:format(self.type.maglevel, getItemNameById(self.type.itemtype))) return end for skillid, value in pairs(self.type.skills) do if getPlayerSkillLevel(cid, skillid) < value then status = false doPlayerSendTextMessage(cid, self.messages.class, self.messages.needskill:format(SKILL_NAMES[skillid], getItemNameById(self.type.itemtype))) break end end end if status == true then for _, item in ipairs(self.type.items) do local thing = getTileItemById(self.position, item[1]) doRemoveItem(thing.uid, item[2]) end doSendMagicEffect(self.position, self.magicEffect) doPlayerSendTextMessage(cid, self.messages.class, self.messages.success:format(getItemNameById(self.type.itemtype))) doCreateItem(self.type.itemtype, self.position) end end dofile(getDataDir() .."/lib/recipes.lua") Crie um arquivo em data/lib chamado recipes.lua e adicione o conteúdo abaixo:
        ---------------------------------------- -----** TUTORIAL DE CONFIGURAÇÃO **----- ---------------------------------------- --[[ O 'ADVANCED FORGE SYSTEM' é muito fácil e intuitivo de configurar, você só precisa chamar a função RecipeHandler:new(...), sendo que você já configurar os atributos da receita nela ou usar outras funções para isso. Por exemplo, quero criar uma Magic Sword que precise de 100 Gold Nuggets. RecipeHandler:new(2400, {{2157, 100}}) Ou então Magic_Sword = RecipeHandler:new() Magic_Sword:setItem(2400) Magic_Sword:setRecipe({2157, 100}) Funções do Sistema: RecipeHandler:new(itemtype, items, level, maglevel, skills) --> Cria uma nova instância de forja. RecipeHandler:setItem(itemtype) --> Atribui um certo itemid como resultado da receita. RecipeHandler:setRecipe(recipe) --> Atribui uma receita. RecipeHandler:setRecipeItem(itemid, amount) --> Adiciona um itemid e sua quantidade a receita. RecipeHandler:setSkill(skillid, value) --> Atribui um valor necessário de uma certa skill para poder criar a receita. RecipeHandler:setLevel(value) --> Atribui o level necessário para criar uma receita. RecipeHandler:setMagLevel(value) --> Atribui o magic level necessário para criar uma receita. ]]-- --[[ Este é um exemplo de receita usando algumas funções. É uma Magic Sword (ITEMID: 2400) que precisa de 100 Gold Nuggets (ITEMID: 2157), além disso, o personagem que tentar forjar, precisa ter Level 100 e Sword Fighting 50. ]]-- Recipes = {} magicsword = RecipeHandler:new() magicsword:setItem(2400) magicsword:setRecipeItem(2157, 100) magicsword:setLevel(100) magicsword:setSkill(2, 50) Agora em data/actions/scripts, crie um arquivo chamado iron_hammer.lua e adicione o conteúdo abaixo:
        function onUse(cid, item, fromPosition, itemEx, toPosition) local recipe = nil for _, v in ipairs(Recipes) do recipe = v:get(toPosition) if(recipe ~= false) then break end end if(recipe) then recipe:create(cid) else doPlayerSendCancel(cid, "This is not a valid recipe.") end return true end E por fim em actions.xml, adicione a seguinte linha:
        <action itemid="4846" event="script" value="iron_hammer.lua"/> OPCIONAL - TALKACTION A talkaction abaixo mostra ao jogadoras receitas configuradas no servidor que ele pode fazer. Em data/talkactions/scripts, crie um arquivo chamado recipes.lua e adicione o conteúdo abaixo:
        function onSay(cid, words, param, channel) local ret = {} local msg = " ADVANCED FORGE SYSTEM\n" for _, recipe in ipairs(Recipes) do local skills = true for skillid, value in pairs(recipe.skills) do if getPlayerSkillLevel(cid, skillid) < value then skills = false break end end if skills == true then if getPlayerLevel(cid) >= recipe.level and getPlayerMagLevel(cid) >= recipe.maglevel then table.insert(ret, {recipe, true}) else table.insert(ret, {recipe, false}) end else table.insert(ret, {recipe, false}) end end for _, recipe in ipairs(ret) do msg = msg .."\nRecipe for ".. getItemNameById(recipe[1].itemtype) ..":\n\n" if recipe[2] == true then for _, item in ipairs(recipe[1].items) do msg = msg .."* ".. getItemNameById(item[1]) .." [".. math.min(item[2], math.max(0, getPlayerItemCount(cid, item[1]))) .."/".. item[2] .."]\n" end else msg = msg .."[LOCKED]\n" end end doShowTextDialog(cid, 2555, msg) return true end Em data/talkactions/talkactions.xml, adicione a linha:
        <talkaction words="/recipes" event="script" value="recipes.lua"/> Siga as instruções para configuração de novas receitas.
      Em breve vídeo de funcionamento
      Advanced Forge System.rar
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo