Ir para conteúdo
  • Cadastre-se

L3K0T

Moderador
  • Total de itens

    2088
  • Registro em

  • Última visita

  • Dias Ganhos

    83

Posts postados por L3K0T

  1. 7 horas atrás, Gabrielx17 disse:

    [12/04/2024 22:20:31] [Error - Spell Interface] 
    [12/04/2024 22:20:31] In a timer event called from: 
    [12/04/2024 22:20:31] data/spells/scripts/maito gai/hachimon_tonkou.lua:onCastSpell
    [12/04/2024 22:20:31] Description: 
    [12/04/2024 22:20:31] data/spells/scripts/maito gai/hachimon_tonkou.lua:209: attempt to call global 'isPlayerLoggedIn' (a nil value)
    [12/04/2024 22:20:31] stack traceback:
    [12/04/2024 22:20:31]     data/spells/scripts/maito gai/hachimon_tonkou.lua:209: in function <data/spells/scripts/maito gai/hachimon_tonkou.lua:208>

     

    da esse erro na distro e esta setando somente a primeira storage (1) o resto fica tudo -1 -1 -1 -1

     

     

    logout:
     

    local storage = 55512 -- Storage para controlar a spell
        local stages = {20, 30, 40} -- Tempos de duração para cada estágio em segundos
        local remainingTime = exhaustion.get(cid, storage) -- Obtém o tempo restante da spell
    
        local stage = 1
    
        for i, stageDuration in ipairs(stages) do
            if remainingTime <= stageDuration then
                stage = i
                break
            end
            remainingTime = remainingTime - stageDuration
        end
    
        -- Salva o estágio e o tempo restante da spell no storage do jogador
        setPlayerStorageValue(cid, storage, stage)
        exhaustion.set(cid, storage, remainingTime)

     

     

    login
     

    local storage = 55512 -- Storage para controlar a spell
        local stages = {20, 30, 40} -- Tempos de duração para cada estágio em segundos
        local remainingTime = getPlayerStorageValue(cid, storage) or 0 -- Obtém o tempo restante da spell do storage
    
        local stage = 1
        -- Determina o estágio com base no tempo restante
        for i, stageDuration in ipairs(stages) do
            if remainingTime <= stageDuration then
                stage = i
                break
            end
            remainingTime = remainingTime - stageDuration
        end
    
        -- Restaura o estágio da spell para o jogador
        setPlayerStorageValue(cid, storage, stage)
        exhaustion.set(cid, storage, remainingTime)

     

     

    spells

     

    function onCastSpell(cid, var)
        local storage = 55512 -- Storage para controlar a spell
        local stage = getPlayerStorageValue(cid, storage) or 0 -- Obtém o estágio atual da spell, se não houver nenhum, assume 0
        local waittimes = {20, 30, 40} -- Tempos de espera para cada estágio em segundos
        
      
        if stage > 0 then
            doPlayerSendCancel(cid, "Você já está sob o efeito da spell.")
            return false
        end 
    
        if not isCreature(cid) then
            return false
        end
    
        -- Definir o estágio inicial da spell
        setPlayerStorageValue(cid, storage, 1)
        stage = 1
    
        -- Função para avançar para o próximo estágio após o término do atual
        local function advanceStage()
            if stage < #waittimes then
                stage = stage + 1
                setPlayerStorageValue(cid, storage, stage)
                -- Programar o próximo avanço de estágio
                addEvent(advanceStage, waittimes[stage] * 1000)
            else
                -- Resetar a storage quando todos os estágios terminarem
                setPlayerStorageValue(cid, storage, -1)
            end
        end
    
        -- Iniciar o avanço de estágio
        addEvent(advanceStage, waittimes[stage] * 1000)
    
    
        -- Definir a exhaustion e aplicar os efeitos iniciais da spell
        local waittime = waittimes[1] -- Definir o tempo de exhaustion baseado no primeiro estágio
        exhaustion.set(cid, storage, waittime)
        OpenGate(cid, Select_Stages(getCreatureOutfit(cid).lookType), 1)
        
        -- Definir a storage de volta para -1 após o término do efeito da spell
        addEvent(function()
            setPlayerStorageValue(cid, storage, -1)
        end, waittime * 1000) -- Convertendo segundos para milissegundos
        
        return true
    end



     

  2. 47 minutos atrás, Gabrielx17 disse:

    Perfeito mano dei uma ajeitada aqui consegui!

    Obrigado voce é zika 

    rep+ pra voce até eu n puder mais!

    Na verdade eu so não consegui uma coisa, quando o player desloga ou morre ele n consegue mais usar a spell pq fica setada em um numero e não volta qnd morre ou desloga se conseguir dar uma força ai agradeço ta me ajudando pra caramba kkkk so tenho a te agradecer!

      Mostrar conteúdo oculto

    function onCastSpell(cid, var)
        local storage = 55512 -- Storage para controlar a spell
        local stage = getPlayerStorageValue(cid, storage) or 0 -- Obtém o estágio atual da spell, se não houver nenhum, assume 0
        local waittimes = {30, 30, 40, 50, 60} -- Tempos de espera para cada estágio em segundos
        local storage2 = 55513
        local waittime3 = 310
      
        if exhaustion.check(cid, storage2) then
        doPlayerSendCancel(cid, "Aguarde " .. exhaustion.get(cid, storage2) .. " segundos para usar a spell novamente.")
        return false
        end
      
          if not isCreature(cid) then
            return false
        end
      
        if stage > 0 then
            doPlayerSendCancel(cid, "Você já está sob o efeito da spell.")
            return false
        end 

        -- Definir o estágio inicial da spell
        setPlayerStorageValue(cid, storage, 1)
        stage = 1

        -- Função para avançar para o próximo estágio após o término do atual
        local function advanceStage()
            if stage < #waittimes then
                stage = stage + 1
                setPlayerStorageValue(cid, storage, stage)
                -- Programar o próximo avanço de estágio
                addEvent(advanceStage, waittimes[stage] * 1000)
            else
                -- Resetar a storage quando todos os estágios terminarem
                setPlayerStorageValue(cid, storage, -1)
            end
        end

        -- Iniciar o avanço de estágio
        addEvent(advanceStage, waittimes[stage] * 1000)


        -- Definir a exhaustion e aplicar os efeitos iniciais da spell
        local waittime = waittimes[1] -- Definir o tempo de exhaustion baseado no primeiro estágio
        exhaustion.set(cid, storage2, waittime3)
        OpenGate(cid, Select_Stages(getCreatureOutfit(cid).lookType), 1)
        
        -- Definir a storage de volta para -1 após o término do efeito da spell
        addEvent(function()
            setPlayerStorageValue(cid, storage, -1)
        end, waittime * 1000) -- Convertendo segundos para milissegundos
        
        return true
    end

    eu deixei assim e ta funcionando perfeitamente aqui, os unicos problemas são o loggout, caso se o player morrer ou deslogar durante a spell(buff), ele fica impossibilitado de usar a spell(buff)

    tem como dar uma força?

    
        local storage = 55512 -- Storage para controlar a spell
        local stage = getPlayerStorageValue(cid, storage)
        if stage and stage > 0 then
            local waittimes = {20, 30, 40, 50} -- Tempos de espera para cada estágio em segundos
            local remainingTime = (waittimes[stage] - (os.time() - getPlayerStorageValue(cid, storage .. "time"))) -- Tempo restante em segundos
            if remainingTime > 0 then
                addEvent(function()
                    doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você está sob o efeito do estágio " .. stage .. " da spell.")
                end, 1000)
                addEvent(function()
                    setPlayerStorageValue(cid, storage, -1)
                end, remainingTime * 1000) -- Definir a storage de volta para -1 após o término do efeito da spell
            end
        end

    coloca no login.lua ^^^^^^^

    function onCastSpell(cid, var)
        local storage = 55512 -- Storage para controlar a spell
        local stage = getPlayerStorageValue(cid, storage) or 0 -- Obtém o estágio atual da spell, se não houver nenhum, assume 0
        local waittimes = {20, 30, 40, 50} -- Tempos de espera para cada estágio em segundos
        
        -- Verificar se o jogador já usou a spell
        if stage > 0 then
            doPlayerSendCancel(cid, "Você já está sob o efeito da spell.")
            return false
        end 
    
        if not isCreature(cid) then
            return false
        end
    
        -- Definir o estágio inicial da spell
        setPlayerStorageValue(cid, storage, 1)
        stage = 1
    
        local function advanceStage()
            if isPlayerLoggedIn(cid) then -- Verificar se o jogador está logado antes de avançar de estágio
                if stage < #waittimes then
                    stage = stage + 1
                    setPlayerStorageValue(cid, storage, stage)
                    -- Programar o próximo avanço de estágio
                    addEvent(advanceStage, waittimes[stage] * 1000)
                    doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você avançou para o estágio " .. stage .. " da spell.")
                else
                    -- Resetar a storage quando todos os estágios terminarem
                    setPlayerStorageValue(cid, storage, -1)
                end
            else
                -- O jogador desconectou, interromper o avanço de estágio
                setPlayerStorageValue(cid, storage, stage) -- Salvar o estágio atual
            end
        end
    
    
        addEvent(advanceStage, waittimes[stage] * 1000)
    
    
    
    
        local waittime = waittimes[1] -- Definir o tempo de exhaustion baseado no primeiro estágio
        exhaustion.set(cid, storage, waittime)
        OpenGate(cid, Select_Stages(getCreatureOutfit(cid).lookType), 1)
        doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você está sob o efeito do estágio 1 da spell.")
        
    
        addEvent(function()
            setPlayerStorageValue(cid, storage, -1)
        end, waittime * 1000) -- Convertendo segundos para milissegundos
        
        return true
    end

    spells.luaa ^^

  3. 1 hora atrás, Gabrielx17 disse:

    --ultimo edit--

    obrigado mano funcionou perfeitamente vc é fera!!!

    uma pergunta eu consigo usar esse addevent para setar storage em etapas? tipo:

    storage 55512 = 1 por 20 segundos

    storage 55512 = 2 por 30 segundos

    storage 55512 = 3 por 40 segundos

    no caso seria quando o player usar a spell

    tipo usei spell susano(buff)

    ai no momento q eu usei daria 55512 = 1 por 20 segundos

    ai acabando os 20 segundos:

    ja iria pra storage 55512 = 2 por 30 segundos

    e acabando os 30 segundos:

     55512 = 3 por 40 segundos

    function onCastSpell(cid, var)
        local storage = 55512 -- Storage para controlar a spell
        local stage = getPlayerStorageValue(cid, storage) or 0 -- Obtém o estágio atual da spell, se não houver nenhum, assume 0
        local waittimes = {20, 30, 40} -- Tempos de espera para cada estágio em segundos
        
      
        if stage > 0 then
            doPlayerSendCancel(cid, "Você já está sob o efeito da spell.")
            return false
        end 
    
        if not isCreature(cid) then
            return false
        end
    
        -- Definir o estágio inicial da spell
        setPlayerStorageValue(cid, storage, 1)
        stage = 1
    
        -- Função para avançar para o próximo estágio após o término do atual
        local function advanceStage()
            if stage < #waittimes then
                stage = stage + 1
                setPlayerStorageValue(cid, storage, stage)
                -- Programar o próximo avanço de estágio
                addEvent(advanceStage, waittimes[stage] * 1000)
            else
                -- Resetar a storage quando todos os estágios terminarem
                setPlayerStorageValue(cid, storage, -1)
            end
        end
    
        -- Iniciar o avanço de estágio
        addEvent(advanceStage, waittimes[stage] * 1000)
    
    
        -- Definir a exhaustion e aplicar os efeitos iniciais da spell
        local waittime = waittimes[1] -- Definir o tempo de exhaustion baseado no primeiro estágio
        exhaustion.set(cid, storage, waittime)
        OpenGate(cid, Select_Stages(getCreatureOutfit(cid).lookType), 1)
        
        -- Definir a storage de volta para -1 após o término do efeito da spell
        addEvent(function()
            setPlayerStorageValue(cid, storage, -1)
        end, waittime * 1000) -- Convertendo segundos para milissegundos
        
        return true
    end

     

  4. 19 minutos atrás, Gabrielx17 disse:

    sobre o script, tipo eu queria q depois q acabasse a spell voltasse pra -1 ou para 0 a storage pode ser qualquer um dos dois 0 ou -1, não sei se teria como. é uma spell de buff.

    vejo q você sempre esta ajudando aqui no TK inclusive ja me ajudou muito, não vejo ninguem mais ajudando alem de voce. vou deixar meu rep+ pra voce, sempre ta online ajudando a comunidade, vc é minha esperança😄.

    function onCastSpell(cid, var)
        local waittime = 310 -- Tempo de exhaustion
        local storage = 55512 -- Storage para controlar a spell
    
        -- Verificar se o jogador já usou a spell
        if getPlayerStorageValue(cid, storage) > 0 then
            if exhaustion.check(cid, storage) then
                doPlayerSendCancel(cid, "Aguarde " .. exhaustion.get(cid, storage) .. " segundos para usar a spell novamente.")
            end
            return false
        end 
    
        if not isCreature(cid) then
            return false
        end
    
        exhaustion.set(cid, storage, waittime)
        setPlayerStorageValue(cid, storage, 1)
    
        if not (getCreatureCondition(cid, CONDITION_ATTRIBUTES, 50) or getCreatureCondition(cid, CONDITION_HASTE, 51) or getCreatureCondition(cid, CONDITION_REGENERATION, 52)) then
            OpenGate(cid, Select_Stages(getCreatureOutfit(cid).lookType), 1)
            
            -- Definir a storage de volta para -1 ou 0 após o término do efeito da spell
            addEvent(function()
                setPlayerStorageValue(cid, storage, -1) -- Pode ser -1 ou 0 aqui
            end, waittime * 1000) -- Convertendo segundos para milissegundos
            
            return true
        else
            doPlayerSendCancel(cid, "Você já está transformado.")
            return false
        end
    end

     

  5. Em 10/04/2024 em 18:59, Gabrielx17 disse:

    .Qual servidor ou website você utiliza como base? 

    tfs 0.3.6

    Qual o motivo deste tópico? 

    tentando colocar storage temporaria de 3 min

    Está surgindo algum erro? Se sim coloque-o aqui. 

    então rapaziada ja tentei colocar pra setar 1 na storage 55512, eu até  consegui mas, eu queria q depois q a spell acabasse voltasse pra 0 ou -1 que é o valor normal de todas storages do meu servidor não sei se teria como, abaixo a function da spell.

    estou com um problema q a spell ela muda a outfit do player e no caso estou querendo setar uma storage para o player não poder usar a talkaction que muda de roupa, no caso !saga.

    Você tem o código disponível? Se tiver publique-o aqui: 

    
    function onCastSpell(cid, var)
    local waittime = 310 -- Tempo de exhaustion
    local storage = 55512 -- não mecha
    if getPlayerStorageValue(cid, storage) > 0 then
    if exhaustion.check(cid, storage) then
    doPlayerSendCancel(cid, "Aguarde " .. exhaustion.get(cid, storage) .. " segundos para usar a spell novamente.")
    end
    return false
    end 
    	if (not isCreature(cid)) then
    		return false
    	end
    	exhaustion.set(cid, storage, waittime)
    	setPlayerStorageValue(cid,storage,1)
    	if getCreatureCondition(cid, CONDITION_ATTRIBUTES, 50) == false and getCreatureCondition(cid, CONDITION_HASTE, 51) == false and getCreatureCondition(cid, CONDITION_REGENERATION, 52) == false then
    		OpenGate(cid, Select_Stages(getCreatureOutfit(cid).lookType), 1)
    		return true
    	else
    		doPlayerSendCancel(cid, "Você já esta transformado.")
    	end
    	return true
    end

     

    Você tem alguma imagem que possa auxiliar no problema? Se sim, coloque-a aqui. 

     

    function onCastSpell(cid, var)
        local waittime = 310 -- Tempo de exhaustion
        local storage = 55512 -- Storage para controlar a spell
    
        -- Verificar se o jogador já usou a spell
        if getPlayerStorageValue(cid, storage) > 0 then
            if exhaustion.check(cid, storage) then
                doPlayerSendCancel(cid, "Aguarde " .. exhaustion.get(cid, storage) .. " segundos para usar a spell novamente.")
            end
            return false
        end 
    
    
        if (not isCreature(cid)) then
            return false
        end
    
     
        exhaustion.set(cid, storage, waittime)
        
    
        setPlayerStorageValue(cid, storage, 1)
    
    
        if not (getCreatureCondition(cid, CONDITION_ATTRIBUTES, 50) or getCreatureCondition(cid, CONDITION_HASTE, 51) or getCreatureCondition(cid, CONDITION_REGENERATION, 52)) then
    
            OpenGate(cid, Select_Stages(getCreatureOutfit(cid).lookType), 1)
            return true
        else
    
            doPlayerSendCancel(cid, "Você já está transformado.")
            return false
        end
    end

     

  6. 9 horas atrás, DigoleraZica disse:

    Bom dia,

     

    Teria como colocar para bloquear de jogar o item em cima de teleports com storage ?

     

    E esse seu em vez de remover o item teria como bloquear também?

    precisa ter um moveitem instalado no seu servidor

     

     

    OU Tente algo como isso
     

    void Teleport::__addThing(Creature* actor, int32_t, Thing* thing)
    {
        if (!thing || thing->isRemoved())
            return;
    
        Tile* destTile = g_game.getTile(destination);
        if (!destTile)
            return;
    
        if (Creature* creature = thing->getCreature())
        {
            g_game.addMagicEffect(creature->getPosition(), MAGIC_EFFECT_TELEPORT, creature->isGhost());
            creature->getTile()->moveCreature(actor, creature, destTile);
            g_game.addMagicEffect(destTile->getPosition(), MAGIC_EFFECT_TELEPORT, creature->isGhost());
        }
        else
        {
            Player* player = dynamic_cast<Player*>(actor);
            if (player)
            {
                player->sendTextMessage(MSG_STATUS_SMALL, "You cannot teleport items.");
            }
            return;
        }
    }
    10 horas atrás, BangxD disse:

    Adorei amigo muito bom 😊 

    obg, bem simples e util ;) 

  7. local COLOR_RED = 180 -- Defina a cor que você está usando
    local tableBoss = {
    	["Amazon"] = {seconds = 10, newBoss = "Amazon"}
    }
    
    local function timer(position, duration)
    	local t = duration
    	addEvent(function()
    		if t > 0 then
    			doSendAnimatedText(position, tostring(t), COLOR_RED)
    			t = t - 1
    			timer(position, t)
    		else
    			-- Respawn do boss após a contagem regressiva
    			addEvent(doCreateMonster, 1000, tableBoss["Amazon"].newBoss, position)
    		end
    	end, 1000)
    end
    
    function onKill(cid, target, damage, flags)
    	if isPlayer(target) then 
    		return true 
    	end
    	local boss = tableBoss[getCreatureName(target)]
    	if not boss then
    		return true
    	end
    	local position = getCreaturePosition(target)
    	local timeLeft = boss.seconds
    	doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_RED, "O boss renascerá em " .. timeLeft .. " segundos na posição: " .. position.x .. ", " .. position.y .. ", " .. position.z) -- Exibe a posição no texto
    	timer(position, boss.seconds)
    	-- Inicia o contador regressivo para o respawn do boss
    	addEvent(function()
    		for i = 1, boss.seconds do
    			addEvent(function()
    				local remainingTime = timeLeft - i
    				if remainingTime > 0 then
    					doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_RED, "O boss renascerá em " .. remainingTime .. " segundos na posição: " .. position.x .. ", " .. position.y .. ", " .. position.z) -- Exibe a posição no texto
    				end
    			end, i * 1000)
    		end
    	end, 1)
    	return true
    end

     

  8. Não jogar itens pelo teleportes C++

     

    1863719719_Semttulo2.png.00eb4eab36c9638b9db35d775d1cf222.png

     

    453658907_Semttulo.png.fd4ff07b186b74c3417eafd476f006ef.png

     

     

    Bom.. o nome já diz, qualquer um que jogar itens nos teleportes do seu otserv, o mesmo será removido, como aquelas lixeiras, porem esse sistema é pela source, descartando scripts .LUA.

     

     

    Em teleporte.cpp ache:
     

    void Teleport::__addThing(Creature* actor, int32_t, Thing* thing)
    {
    	if(!thing || thing->isRemoved())
    		return;
    
    	Tile* destTile = g_game.getTile(destination);
    	if(!destTile)
    		return;
    
    	if(Creature* creature = thing->getCreature())
    	{
    		g_game.addMagicEffect(creature->getPosition(), MAGIC_EFFECT_TELEPORT, creature->isGhost());
    		creature->getTile()->moveCreature(actor, creature, destTile);
    		g_game.addMagicEffect(destTile->getPosition(), MAGIC_EFFECT_TELEPORT, creature->isGhost());
    	}
    	else if(Item* item = thing->getItem())
    	{
    		g_game.addMagicEffect(item->getPosition(), MAGIC_EFFECT_TELEPORT);
    		g_game.internalMoveItem(actor, item->getTile(), destTile, INDEX_WHEREEVER, item, item->getItemCount(), NULL);
    		g_game.addMagicEffect(destTile->getPosition(), MAGIC_EFFECT_TELEPORT);
    	}
    }

     

    Altere ele todo para:

     

    void Teleport::__addThing(Creature* actor, int32_t, Thing* thing)
    {
        if (!thing || thing->isRemoved())
            return;
    
        Tile* destTile = g_game.getTile(destination);
        if (!destTile)
            return;
    
        if (Creature* creature = thing->getCreature())
        {
            g_game.addMagicEffect(creature->getPosition(), MAGIC_EFFECT_TELEPORT, creature->isGhost());
            creature->getTile()->moveCreature(actor, creature, destTile);
            g_game.addMagicEffect(destTile->getPosition(), MAGIC_EFFECT_TELEPORT, creature->isGhost());
        }
        else
        {
            Player* player = dynamic_cast<Player*>(actor);
            if (player)
            {
                player->sendTextMessage(MSG_STATUS_SMALL, "You cannot teleport items.");
    			
    			// Remover o item
                Item* item = dynamic_cast<Item*>(thing);
                if (item) {
                    g_game.internalRemoveItem(actor, item);
                }
            }
            return;
        }
    }

    agora é só compilar no modo Rebuilder e ligar o servidor, créditos a mim L3K0T pela alterações.

  9. 21 horas atrás, HexusAlphos disse:

    tá dando esse erro

    Screenshot_2.thumb.png.31f5f12e6e3dc74eed4fe02a914e07bd.png

    function onStepIn(cid, item, position, fromPosition)
        if not isPlayer(cid) then
            return false
        end
    
        local playerPosition = getCreaturePosition(cid)
        local vocation = getPlayerVocation(cid)
    
        -- Defina as habilidades correspondentes para cada vocação
        local skillsToTrain = {
            [0] = {1, 2}, -- Vocação sem classe
            [1] = {1, 2}, -- Knight
            [2] = {3}, -- Paladin
            [3] = {4}, -- Sorcerer
            [4] = {4}, -- Druid
            [5] = {4}, -- Master Sorcerer
            [6] = {4} -- Elder Druid
        }
    
        local minSkill = 10 -- Substitua 10 pelo valor mínimo da habilidade para começar a treinar
        local gainChance = 50 -- Chance de ganhar skill, em porcentagem
        local requiredItemID = 1234 -- Substitua 1234 pelo ID do item necessário para treinar aqui
    
        if not skillsToTrain[vocation] then
            return false
        end
    
        for _, skillToTrain in ipairs(skillsToTrain[vocation]) do
            local skillLevel = getPlayerSkillLevel(cid, skillToTrain)
    
            if skillLevel < minSkill then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não tem a habilidade necessária para treinar aqui.")
                return true
            end
    
            -- Verifica se o jogador está equipado com o item necessário
            local rightSlotItem = getPlayerSlotItem(cid, CONST_SLOT_RIGHT)
            if not rightSlotItem or rightSlotItem.itemid ~= requiredItemID then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você precisa estar equipado com o item necessário para treinar aqui.")
                return true
            end
    
            -- Verifica se o jogador está na posição correta
            if not isInRange(playerPosition, position, 1) then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não está na posição correta para treinar.")
                return true
            end
    
            -- Adiciona um evento para ganhar skill a cada 3 segundos
            local event = addEvent(function()
                -- Verifica se o jogador ainda está na posição correta
                local currentPlayerPosition = getCreaturePosition(cid)
                if not isInRange(currentPlayerPosition, position, 1) then
                    -- Se o jogador não estiver mais na posição, cancela o evento e remove da tabela de eventos
                    if skillEvents[cid] then
                        stopEvent(skillEvents[cid])
                        skillEvents[cid] = nil
                    end
                    return
                end
    
                -- Verifica se o jogador ganha skill
                if math.random(100) <= gainChance then
                    doPlayerAddSkillTry(cid, skillToTrain)
                    doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                else
                    doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                end
            end, 3000) -- 3000 milissegundos = 3 segundos
            
            -- Armazena o evento na tabela de eventos, associando ao jogador
            skillEvents[cid] = event
        end
    
        return true
    end
    
    function onLogout(cid)
        -- Verifica se o jogador está na tabela de eventos
        if skillEvents[cid] then
            -- Cancela o evento temporizado e remove da tabela de eventos
            stopEvent(skillEvents[cid])
            skillEvents[cid] = nil
        end
        return true
    end

     

  10. 1 hora atrás, HexusAlphos disse:

     

     

    Desculpa tá enchendo o saco, mas como seria esse script sem a parte de vocation? É um tile que só vai treinar uma skill para todas as vocations do servidor (existem muitas)

     

           [0] = {1, 2}, -- Vocação sem classe vai trenr skill 1 e 2
            [1] = {1, 2}, -- Knight vai trenr skill 1 e 2
            [2] = {3}, -- Paladin vai trenr skill 3
            [3] = {4}, -- Sorcerer vai trenarr skill 4 ml
            [4] = {4}, -- Druid vai trenarr skill 4 ml
            [5] = {4}, -- Master Sorcerer vai trenarr skill 4 ml
            [6] = {4} -- Elder Druid vai trenarr skill 4 ml

    coloquei tempo em tempo pra subir

     

    local skillEvents = {} -- Tabela para armazenar os eventos temporizados por jogador
    
    function onStepIn(cid, item, position, fromPosition)
        if not isPlayer(cid) then
            return false
        end
    
        local playerPosition = getCreaturePosition(cid)
        local vocation = getPlayerVocation(cid)
    
        -- Defina as habilidades correspondentes para cada vocação
        local skillsToTrain = {
            [0] = {1, 2}, -- Vocação sem classe
            [1] = {1, 2}, -- Knight
            [2] = {3}, -- Paladin
            [3] = {4}, -- Sorcerer
            [4] = {4}, -- Druid
            [5] = {4}, -- Master Sorcerer
            [6] = {4} -- Elder Druid
        }
    
        local minSkill = 10 -- Substitua 10 pelo valor mínimo da habilidade para começar a treinar
        local gainChance = 50 -- Chance de ganhar skill, em porcentagem
        local requiredItemID = 1234 -- Substitua 1234 pelo ID do item necessário para treinar aqui
    
        if not skillsToTrain[vocation] then
            return false
        end
    
        for _, skillToTrain in ipairs(skillsToTrain[vocation]) do
            local skillLevel = getPlayerSkillLevel(cid, skillToTrain)
    
            if skillLevel < minSkill then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não tem a habilidade necessária para treinar aqui.")
                return true
            end
    
            -- Verifica se o jogador está equipado com o item necessário
            local rightSlotItem = getPlayerSlotItem(cid, CONST_SLOT_RIGHT)
            if not rightSlotItem or rightSlotItem.itemid ~= requiredItemID then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você precisa estar equipado com o item necessário para treinar aqui.")
                return true
            end
    
            -- Verifica se o jogador está na posição correta
            if not isInRange(playerPosition, position, 1) then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não está na posição correta para treinar.")
                return true
            end
    
            -- Adiciona um evento para ganhar skill a cada 3 segundos
            local event = addEvent(function()
                -- Verifica se o jogador ainda está na posição correta
                local currentPlayerPosition = getCreaturePosition(cid)
                if not isInRange(currentPlayerPosition, position, 1) then
                    -- Se o jogador não estiver mais na posição, cancela o evento e remove da tabela de eventos
                    if skillEvents[cid] then
                        stopEvent(skillEvents[cid])
                        skillEvents[cid] = nil
                    end
                    return
                end
    
                -- Verifica se o jogador ganha skill
                if math.random(100) <= gainChance then
                    doPlayerAddSkillTry(cid, skillToTrain)
                    doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                else
                    doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                end
            end, 3000) -- 3000 milissegundos = 3 segundos
            
            -- Armazena o evento na tabela de eventos, associando ao jogador
            skillEvents[cid] = event
        end
    
        return true
    end
    
    function onLogout(cid)
        -- Verifica se o jogador está na tabela de eventos
        if skillEvents[cid] then
            -- Cancela o evento temporizado e remove da tabela de eventos
            stopEvent(skillEvents[cid])
            skillEvents[cid] = nil
        end
        return true
    end

     

  11. Em 17/03/2024 em 23:15, JhonnySeth7 disse:

    .Qual servidor ou website você utiliza como base? 

     

    Qual o motivo deste tópico? 

    AJUDA AI GALERA N SEI OQ FAZER

     

    Está surgindo algum erro? Se sim coloque-o aqui. 

     

    Você tem o código disponível? Se tiver publique-o aqui: 

    
     function onUse(cid, item, frompos, item2, topos)
        local itemids = {
            [1] = 26383, -- cabeça
            [4] = 26384, -- armor
            [5] = 26387, -- direita
            [6] = 26388, -- esquerda
            [7] = 26385, -- legs
            [8] = 26386  -- boots
        }
        
        local storage = 26427 -- storage que vai ser usada pra salvar se o player já usou ou não
        local outfit = 907 -- outfit que vai dar
        local newVocation = 10 -- ID da nova vocation ao usar o storage
        local bagId = 26427 -- ID do saco onde os itens devem ser devolvidos
    
        if getPlayerStorageValue(cid, storage) ~= 1 then
            for i = 1, 8 do
                if i ~= 2 and i ~= 3 then
                    local item = getPlayerSlotItem(cid, i)
                    if item.itemid > 0 then
                        doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Seus itens foram devolvidos para o saco de itens.")
                        doAddContainerItem(bagId, item.itemid, item.type, item.count)
                        doRemoveItem(item.uid)
                    end
                    doPlayerAddItem(cid, itemids[i], 1, false)
                end
            end
            doSetCreatureOutfit(cid, {lookType = outfit}, -1)
            doPlayerSetVocation(cid, newVocation)
            setPlayerStorageValue(cid, storage, 1)
        else
            for i = 1, 8 do
                if i ~= 2 and i ~= 3 then
                    local item = getPlayerSlotItem(cid, i)
                    if item.itemid > 0 then
                        doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Seus itens foram devolvidos para o saco de itens.")
                        doAddContainerItem(bagId, item.itemid, item.type, item.count)
                        doRemoveItem(item.uid)
                    end
                end
            end
            doRemoveCondition(cid, CONDITION_OUTFIT)
            doPlayerSetVocation(cid, 1) -- Voltar à vocation 1
            setPlayerStorageValue(cid, storage, 0)
        end
        
        return true
    end

     

    Você tem alguma imagem que possa auxiliar no problema? Se sim, coloque-a aqui. 

     

     

    Isso está ocorrendo porque o contêiner com o ID `bagId` não foi criado antes de tentar adicionar itens a ele. 

     


     

    function onUse(cid, item, frompos, item2, topos)
        local itemids = {
            [1] = 26383, -- cabeça
            [4] = 26384, -- armadura
            [5] = 26387, -- direita
            [6] = 26388, -- esquerda
            [7] = 26385, -- pernas
            [8] = 26386  -- botas
        }
        
        local storage = 26427 -- armazenamento usado para salvar se o jogador já usou ou não
        local outfit = 907 -- visual a ser dado
        local novaVocação = 10 -- ID da nova vocação ao usar o armazenamento
        local bagId = 26427 -- ID do saco onde os itens devem ser devolvidos
    
        local containerItems = {}
    
        if getPlayerStorageValue(cid, storage) ~= 1 then
            for i = 1, 8 do
                if i ~= 2 and i ~= 3 then
                    local playerItem = getPlayerSlotItem(cid, i)
                    if playerItem.itemid > 0 then
                        containerItems[#containerItems + 1] = playerItem
                        doPlayerAddItem(cid, itemids[i], 1, false)
                    end
                end
            end
            doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Seus itens foram devolvidos para o saco de itens.")
            local container = doCreateItemEx(2853, 1)
            for _, item in ipairs(containerItems) do
                doAddContainerItem(container.uid, item.itemid, item.type, item.count)
                doRemoveItem(item.uid)
            end
            doPlayerAddItem(cid, container, 1, false)
            doSetCreatureOutfit(cid, {lookType = outfit}, -1)
            doPlayerSetVocation(cid, novaVocação)
            setPlayerStorageValue(cid, storage, 1)
        else
            doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Seus itens foram devolvidos para o saco de itens.")
            local container = doCreateItemEx(2853, 1)
            for i = 1, 8 do
                if i ~= 2 and i ~= 3 then
                    local playerItem = getPlayerSlotItem(cid, i)
                    if playerItem.itemid > 0 then
                        doAddContainerItem(container.uid, playerItem.itemid, playerItem.type, playerItem.count)
                        doRemoveItem(playerItem.uid)
                    end
                end
            end
            doPlayerAddItem(cid, container, 1, false)
            doRemoveCondition(cid, CONDITION_OUTFIT)
            doPlayerSetVocation(cid, 1) -- Voltar à vocação 1
            setPlayerStorageValue(cid, storage, 0)
        end
        
        return true
    end

     

  12. function onStepIn(cid, item, position, fromPosition)
        if not isPlayer(cid) then
            return false
        end
    
        local playerPosition = getCreaturePosition(cid)
        local vocation = getPlayerVocation(cid)
    
        -- Defina as habilidades correspondentes para cada vocação
        local skillsToTrain = {
            [0] = {1, 2}, -- Vocação sem classe
            [1] = {1, 2}, -- Knight
            [2] = {3}, -- Paladin
            [3] = {4}, -- Sorcerer
            [4] = {4}, -- Druid
            [5] = {4}, -- Master Sorcerer
            [6] = {4} -- Elder Druid
        }
    
        local minSkill = 10 -- Substitua 10 pelo valor mínimo da habilidade para começar a treinar
        local gainChance = 50 -- Chance de ganhar skill, em porcentagem
        local requiredItemID = 1234 -- Substitua 1234 pelo ID do item necessário para treinar
    
        if not skillsToTrain[vocation] then
            return false
        end
    
        for _, skillToTrain in ipairs(skillsToTrain[vocation]) do
            local skillLevel = getPlayerSkillLevel(cid, skillToTrain)
    
            if skillLevel < minSkill then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não tem a habilidade necessária para treinar aqui.")
                return true
            end
    
            -- Verifica se o jogador está equipado com o item necessário
            local rightSlotItem = getPlayerSlotItem(cid, CONST_SLOT_RIGHT)
            if not rightSlotItem or rightSlotItem.itemid ~= requiredItemID then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você precisa estar equipado com o item necessário para treinar aqui.")
                return true
            end
    
            -- Verifica se o jogador está na posição correta
            if not isInRange(playerPosition, position, 1) then
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não está na posição correta para treinar.")
                return true
            end
    
            -- Verifica se o jogador ganha skill
            if math.random(100) <= gainChance then
                doPlayerAddSkillTry(cid, skillToTrain)
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
            else
                doPlayerSendTextMessage(cid, MESSAGE_EVENT_DEFAULT, "Você não ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
            end
        end
    
        return true
    end

     

  13. Em 29/03/2024 em 19:10, Muvukaa disse:
    
    local combat = createCombatObject()
    setCombatParam(combat, COMBAT_PARAM_TYPE, COMBAT_DEATHDAMAGE)
    setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MORTAREA)
    setCombatParam(combat, COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_SUDDENDEATH)
    
    function damage(cid, level, maglevel)
        local min = 1000000000
        local max = 1000000000
        return -min, -max
    end
    setCombatCallback(combat, CALLBACK_PARAM_LEVELMAGICVALUE, "damage")
    
    function onCastSpell(cid, var)
        return doCombat(cid, combat, var)
    end
    
    local area = {
        {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
        {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
        {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
        {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
        {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
        {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
        {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
        {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
        {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0},
        {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
    }
    local combatArea = createCombatArea(area)
    setCombatArea(combat, combatArea)
    
    function onCastSpell(cid, var)
        return doCombat(cid, combat, var)
    end

     

    Isso??

     

    local combat = createCombatObject()
    setCombatParam(combat, COMBAT_PARAM_TYPE, COMBAT_DEATHDAMAGE)
    setCombatParam(combat, COMBAT_PARAM_EFFECT, CONST_ME_MORTAREA)
    setCombatParam(combat, COMBAT_PARAM_DISTANCEEFFECT, CONST_ANI_SUDDENDEATH)
    
    function damage(cid, level, maglevel, targetPosition)
        local min = 1000000000
        local max = 1000000000
        return -min, -max, getDirectionTo(targetPosition) -- Retorna também a direção para o alvo
    end
    setCombatCallback(combat, CALLBACK_PARAM_LEVELMAGICVALUE, "damage")
    
    function onCastSpell(cid, var)
        local target = variantToPosition(var)
        local targetCreature = getTopCreature(target).uid
        local direction = getDirectionTo(getCreaturePosition(targetCreature))
        local newVar = createCombatArea(getAreaAround(target, 1, 1)) -- Define a área de ataque em torno do alvo
        setCombatArea(combat, newVar)
        return doCombat(cid, combat, var), direction
    end
    
    -- Função auxiliar para obter a direção para uma posição alvo
    function getDirectionTo(targetPosition)
        local creaturePosition = getCreaturePosition(cid)
        local dx = targetPosition.x - creaturePosition.x
        local dy = targetPosition.y - creaturePosition.y
    
        if math.abs(dx) > math.abs(dy) then
            if dx > 0 then
                return DIRECTION_EAST
            else
                return DIRECTION_WEST
            end
        else
            if dy > 0 then
                return DIRECTION_SOUTH
            else
                return DIRECTION_NORTH
            end
        end
    end

     

  14. Como diz o título? Você pode gerar as funções do seu TFS em um arquivo de texto. Para fazer isso, basta ir em uma das bibliotecas (LIB) e adicionar o seguinte código no final. 

     

    -- Função para obter todas as funções disponíveis no ambiente Lua
    function getLuaFunctions()
        local function iterateTable(tbl, prefix)
            local str = ""
            for key, value in pairs(tbl) do
                if type(value) == 'function' then
                    str = str .. prefix .. key .. ','
                elseif type(value) == 'table' then
                    str = str .. iterateTable(value, prefix .. key .. '.')
                end
            end
            return str
        end

        local str = iterateTable(_G, "")
        return string.explode(str, ',')
    end

    -- Obtém todas as funções disponíveis
    local functionsList = getLuaFunctions()

    -- Ordena a lista de funções
    table.sort(functionsList)

    -- Cria uma string de data no formato 'YYYY-MM-DD'
    local currentDate = os.date('%Y-%m-%d')

    -- Salva a lista de funções em um arquivo de texto com a data atual
    local fileName = 'funcoes_do_seu_servidor_' .. currentDate .. '.txt'
    local file = io.open(fileName, 'w')
    for i, funcName in ipairs(functionsList) do
        if funcName ~= "" then
            file:write((i - 1) .. ' - ' .. funcName .. '\n')
        end
    end
    file:close()

    -- Criado por L3K0T

     

    Depois, é só iniciar o seu servidor e assim todas as funções do seu servidor vão aparecer no arquivo TXT com a data de criação.

     

    "Isso é útil para resolver problemas de scripts e trabalhar de forma mais eficiente, manipulando as funções."

  15. 15 minutos atrás, HexusAlphos disse:

    Alguém possui um script de move que quando um jogador se mover em certo tile, uma skill dele upa como se tivesse treinando com os dunny. 

     

    Exemplo: Vou em um tile equipado com algum item e ao andar naquele tile, minha skill vai subindo como se tivesse treinando

    function onStepIn(creature, item, position, fromPosition)
        local skillToTrain = SKILL_SWORD -- Substitua SKILL_SWORD pela habilidade que você deseja treinar
        local minSkill = 10 -- Substitua 10 pelo valor mínimo da habilidade para começar a treinar
        local gainChance = 50 -- Chance de ganhar skill, em porcentagem
        local requiredItemID = 1234 -- Substitua 1234 pelo ID do item necessário para treinar
    
        if creature:isPlayer() then
            local player = creature:getPlayer()
            
            -- Verifica se o jogador está equipado com o item necessário
            if player:getSlotItem(CONST_SLOT_RIGHT) and player:getSlotItem(CONST_SLOT_RIGHT):getId() == requiredItemID then
                local skillLevel = player:getSkillLevel(skillToTrain)
    
                if skillLevel >= minSkill then
                    -- Verifica se o jogador ganha skill
                    if math.random(100) <= gainChance then
                        player:addSkillTries(skillToTrain, 1)
                        player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                    else
                        player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você não ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                    end
                else
                    player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você não tem a habilidade necessária para treinar aqui.")
                end
            else
                player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você precisa estar equipado com o item necessário para treinar aqui.")
            end
        end
        return true
    end

     

    Ou pra cada vocação

     

    function onStepIn(creature, item, position, fromPosition)
        if creature:isPlayer() then
            local player = creature:getPlayer()
            local vocation = player:getVocation():getId()
    
            -- Defina as habilidades correspondentes para cada vocação
            local skillsToTrain = {
                [VOCATION_NONE] = {SKILL_SWORD, SKILL_SHIELD}, -- Vocação sem classe
                [VOCATION_KNIGHT] = {SKILL_SWORD, SKILL_SHIELD}, -- Cavaleiro
                [VOCATION_PALADIN] = {SKILL_DISTANCE}, -- Paladino
                [VOCATION_SORCERER] = {SKILL_MAGLEVEL}, -- Sorcerer
                [VOCATION_DRUID] = {SKILL_MAGLEVEL}, -- Druida
                [VOCATION_MASTER_SORCERER] = {SKILL_MAGLEVEL}, -- Mestre dos Sorcerer
                [VOCATION_ELDER_DRUID] = {SKILL_MAGLEVEL} -- Mestre dos Druid
            }
    
            local minSkill = 10 -- Substitua 10 pelo valor mínimo da habilidade para começar a treinar
            local gainChance = 50 -- Chance de ganhar skill, em porcentagem
            local requiredItemID = 1234 -- Substitua 1234 pelo ID do item necessário para treinar
    
            if skillsToTrain[vocation] then
                for _, skillToTrain in ipairs(skillsToTrain[vocation]) do
                    local skillLevel = player:getSkillLevel(skillToTrain)
    
                    if skillLevel >= minSkill then
                        -- Verifica se o jogador está equipado com o item necessário
                        if player:getSlotItem(CONST_SLOT_RIGHT) and player:getSlotItem(CONST_SLOT_RIGHT):getId() == requiredItemID then
                            -- Verifica se o jogador ganha skill
                            if math.random(100) <= gainChance then
                                player:addSkillTries(skillToTrain, 1)
                                player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                            else
                                player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você não ganhou experiência em " .. getSkillName(skillToTrain) .. ".")
                            end
                        else
                            player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você precisa estar equipado com o item necessário para treinar aqui.")
                        end
                    else
                        player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Você não tem a habilidade necessária para treinar aqui.")
                    end
                end
            else
                player:sendTextMessage(MESSAGE_EVENT_DEFAULT, "Esta vocação não pode treinar aqui.")
            end
        end
        return true
    end

     

     

     

     

  16. 8 horas atrás, Doria Louro disse:

     

     

    Notei que ao maximizar o console os jogadores voltam a logar, e se o console já estiver maximizado ele minimizo e maximizo novamente e o problema se resolve, como programador e tanto tempo essa situação me frusta pois o que maximizar o console tem haver, alguém já passou por essa situação?

    Meio q pausa o console, parece tipo aquele negócio de segundo plano, tente ver na propriedade do console algo que bloqueia ao minimizar saca? 

  17. Em 24/03/2024 em 08:14, Doria Louro disse:

    Bom dia senhores.

    (Moderadores não sei se postei no local correto)

     

    Gostaria que alguém me ajudasse a entender porque meu TFS 0.4 de repente não deixa jogadores logarem, no distro não é apresentando nenhum erro, continua rodando normalmente, ao efetuar o login na conta a lista de personagem é exibida normalmente porém ao tentar entrar com o personagem no jogo o cliente fica nesta tela para sempre:


    image.png.864101574fee7357dda951cb4b9a4524.png 

     

    Sei que há versões do TFS 1.X mais estáveis, porém tenho muitos scripts próprio e seria uma carga enorme refatorar todos para a versão do TFS 1.X

     

    Quem puder me ajudar estarei enviando um PIX em forma de gratidão, já que esse problema veem me assombrando a algumas semanas.

     

    Att Doria

    Pode ser o banco de dados caindo e voltando aí da erro ninguém entra 🤔

  18. function onSay(cid, words, param, channel)
        local t = {}
        for i = 1, getPlayerInstantSpellCount(cid) do
            local spell = getPlayerInstantSpellInfo(cid, i - 1)
            if(spell.mlevel ~= 1) then
                if(spell.manapercent > 0) then
                    spell.mana = spell.manapercent .. "%"
                end
    
                table.insert(t, spell)
            end
        end
    
        table.sort(t, function(a, b) return a.mlevel < b.mlevel end)
        local text, prevLevel = "", -1
        for i, spell in ipairs(t) do
            local line = ""
            if(prevLevel ~= spell.mlevel) then
                if(i ~= 1) then
                    line = "\n"
                end
    
                line = line .. "Spells for Magic Level " .. spell.mlevel .. "\n"
                prevLevel = spell.mlevel
            end
    
            text = text .. line .. "  " .. spell.words .. " : " .. spell.mana .. "\n"
        end
    
        doShowTextDialog(cid, 2175, text)
        return true
    end

     

  19. <?php
    if (!defined('INITIALIZED')) exit;
    
    // Função para verificar se é hora de resetar os highscores
    function deveResetarHighscores() {
        // Coloque aqui a lógica para determinar se é hora de resetar os highscores
        // Por exemplo, verificar se passou uma certa quantidade de tempo desde o último reset
        // Retorne true se for hora de resetar, caso contrário, retorne false
        $lastResetTimestamp = /* Coloque aqui o timestamp do último reset */;
        $interval = 5 * 60; // 5 minutos em segundos
        $currentTimestamp = time();
    
        // Verifica se passou o intervalo de tempo definido desde o último reset
        return ($currentTimestamp - $lastResetTimestamp) >= $interval;
    }
    
    // Função para resetar os highscores
    function resetarHighscores() {
        // Coloque aqui a lógica para resetar os highscores
        // Por exemplo, atualizar os valores na base de dados ou em outro sistema de armazenamento
        // Certifique-se de realizar as operações necessárias para reiniciar os highscores conforme sua lógica de negócios
    }
    
    $list = 'experience';
    if (isset($_REQUEST['list'])) $list = $_REQUEST['list'];
    
    $page = 0;
    if (isset($_REQUEST['page'])) $page = min(50, $_REQUEST['page']);
    
    $vocation = '';
    if (isset($_REQUEST['vocation'])) $vocation = $_REQUEST['vocation'];
    
    switch ($list) {
        case "fist":
            $id = Highscores::SKILL_FIST;
            $list_name = 'Fist Fighting';
            break;
        case "club":
            $id = Highscores::SKILL_CLUB;
            $list_name = 'Club Fighting';
            break;
        case "sword":
            $id = Highscores::SKILL_SWORD;
            $list_name = 'Sword Fighting';
            break;
        case "axe":
            $id = Highscores::SKILL_AXE;
            $list_name = 'Axe Fighting';
            break;
        case "distance":
            $id = Highscores::SKILL_DISTANCE;
            $list_name = 'Distance Fighting';
            break;
        case "shield":
            $id = Highscores::SKILL_SHIELD;
            $list_name = 'Shielding';
            break;
        case "fishing":
            $id = Highscores::SKILL_FISHING;
            $list_name = 'Fishing';
            break;
        case "magic":
            $id = Highscores::SKILL__MAGLEVEL;
            $list_name = 'Magic';
            break;
        default:
            $id = Highscores::SKILL__LEVEL;
            $list_name = 'Experience';
            break;
    }
    
    $world_name = $config['server']['serverName'];
    $offset = $page * 100;
    $skills = new Highscores($id, 100, $page, $vocation);
    
    $main_content .= '<TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%><TR><TD><IMG SRC="'.$layout_name.'/images/blank.gif" WIDTH=10 HEIGHT=1 BORDER=0></TD><TD><CENTER><H2>Ranking for '.htmlspecialchars($list_name).' on '.htmlspecialchars($world_name).'</H2></CENTER><BR>';
    
    $main_content .= '<br><TABLE BORDER=0 CELLPADDING=4 CELLSPACING=1 WIDTH=100%></TABLE><TABLE BORDER=0 CELLPADDING=4 CELLSPACING=1 WIDTH=100%><TR BGCOLOR="'.$config['site']['vdarkborder'].'"><TD CLASS=whites><B>Rank</B></TD><TD WIDTH=75% CLASS=whites><B>Name</B></TD><TD WIDTH=15% CLASS=whites><b><center>Level</center></B></TD>';
    if ($list == "experience") $main_content .= '<TD CLASS=whites><b><center>Experience</center></B></TD>';
    $main_content .= '</TR>';
    $number_of_rows = 0;
    
    foreach ($skills as $skill) {
        if ($list == "magic") $value = $skill->getMagLevel();
        elseif ($list == "experience") $value = $skill->getLevel();
        else $value = $skill->getScore();
        
        $bgcolor = (($number_of_rows++ % 2 == 1) ? $config['site']['darkborder'] : $config['site']['lightborder']);
        
        $main_content .= '<tr bgcolor="'.$bgcolor.'"><td style="text-align:right">'.($offset + $number_of_rows).'.</td><td><a href="?subtopic=characters&name='.urlencode($skill->getName()).'">'.($skill->getOnline() > 0 ? "<font color=\"green\">".htmlspecialchars($skill->getName())."</font>" : "<font color=\"red\">".htmlspecialchars($skill->getName())."</font>").'</a><br><small>'.$skill->getLevel().' '.htmlspecialchars(Website::getVocationName($skill->getVocation())).'</small></td><td><center>'.$value.'</center></td>';
        
        if ($list == "experience") $main_content .= '<td><center>'.$skill->getExperience().'</center></td>';
        
        $main_content .= '</tr>';
    }
    
    $main_content .= '</TABLE><TABLE BORDER=0 CELLPADDING=4 CELLSPACING=1 WIDTH=100%>';
    if ($page > 0) $main_content .= '<TR><TD WIDTH=100% ALIGN=right VALIGN=bottom><A HREF="?subtopic=highscores&list='.urlencode($list).'&page='.($page - 1).'&vocation=' . urlencode($vocation) . '" CLASS="size_xxs">Previous Page</A></TD></TR>';
    if ($page < 50) $main_content .= '<TR><TD WIDTH=100% ALIGN=right VALIGN=bottom><A HREF="?subtopic=highscores&list='.urlencode($list).'&page='.($page + 1).'&vocation=' . urlencode($vocation) . '" CLASS="size_xxs">Next Page</A></TD></TR>';
    $main_content .= '</TABLE></TD><TD WIDTH=5%><IMG SRC="'.$layout_name.'/images/blank.gif" WIDTH=1 HEIGHT=1 BORDER=0></TD><TD WIDTH=15% VALIGN=top ALIGN=right><TABLE BORDER=0 CELLPADDING=4 CELLSPACING=1><TR BGCOLOR="'.$config['site']['vdarkborder'].'"><TD CLASS=whites><B>Choose a skill</B></TD></TR><TR BGCOLOR="'.$config['site']['lightborder'].'"><TD><A HREF="?subtopic=highscores&list=experience" CLASS="size_xs">Experience</A><BR><A HREF="?subtopic=highscores&list=magic" CLASS="size_xs">Magic</A><BR><A HREF="?subtopic=highscores&list=shield" CLASS="size_xs">Shielding</A><BR><A HREF="?subtopic=highscores&list=distance" CLASS="size_xs">CLASS="size_xs">Distance</A><BR><A HREF="?subtopic=highscores&list=club" CLASS="size_xs">Club</A><BR><A HREF="?subtopic=highscores&list=sword" CLASS="size_xs">Sword</A><BR><A HREF="?subtopic=highscores&list=axe" CLASS="size_xs">Axe</A><BR><A HREF="?subtopic=highscores&list=fist" CLASS="size_xs">Fist</A><BR><A HREF="?subtopic=highscores&list=fishing" CLASS="size_xs">Fishing</A><BR></TD></TR></TABLE></TD><TD><IMG SRC="'.$layout_name.'/images/blank.gif" WIDTH=10 HEIGHT=1 BORDER=0></TD></TR></TABLE>';
    
    // Verifica se é hora de resetar os highscores
    if (deveResetarHighscores()) {
        // Reseta os highscores
        resetarHighscores();
    }
    ?>

     

  20. local POLL_STORAGE = 80000
    local OPTIONS_STORAGE = 80001
    local PLAYER_STORAGE = 80000
    
    function table.serialize(tbl)
        local str = "{"
        local sep = ""
        for k, v in pairs(tbl) do
            str = str .. sep
            if type(k) == "number" then
                str = str .. "[" .. k .. "]"
            else
                str = str .. k
            end
            str = str .. "="
            if type(v) == "table" then
                str = str .. table.serialize(v)
            elseif type(v) == "number" or type(v) == "boolean" then
                str = str .. tostring(v)
            else
                str = str .. string.format("%q", v)
            end
            sep = ","
        end
        str = str .. "}"
        return str
    end
    
    local function getTotalVotes()
       local options = table.unserialize(getStorage(OPTIONS_STORAGE))
       local amount = 0
       for _, option in ipairs(options) do
           amount = amount + option[2]
       end
       return amount
    end
    
    local function getMostVotedOption()
       local options = table.unserialize(getStorage(OPTIONS_STORAGE))
       local value, ret = 0, {}
       for _, option in ipairs(options) do
           if option[2] > value then
               value = option[2]
               ret = {option[1]}
           elseif option[2] == value then
               table.insert(ret, option[1])
           end
       end
       return ret
    end
    
    function onSay(cid, words, param, channel)
       param = param or ""
    
       if param == "" and not words == "/poll" then
           return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "The command ".. words .." need parameters.")
       end
    
       local parameters, vote = {}
       if(words == "/newpoll") then
           if getStorage(POLL_STORAGE) ~= -1 then
               return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Sorry, but there is a poll in progress.\nIf you want to start a new poll, type /endpoll.")
           end
    
           parameters = string.explode(param, ",")
           if #parameters < 3 then
               return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "The command /newpoll needs a poll and at least two options.")
           end
    
           if parameters[1] then
               local options = {}
               for i = 2, #parameters do
                   table.insert(options, {parameters[i], 0})
               end
    
               if #options < 2 then
                   return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Insert at least two options after the poll")
               end
               doSetStorage(POLL_STORAGE, parameters[1])
               options = table.serialize(options)
               doSetStorage(OPTIONS_STORAGE, options)
               doBroadcastMessage("A new poll is in progress with the title '".. getStorage(POLL_STORAGE) .."?'!\nSee the status with /poll and vote with /vote.")
           end
       elseif(words == "/vote") then
           vote = tonumber(param) or -1
           local options = table.unserialize(getStorage(OPTIONS_STORAGE))
           if getStorage(POLL_STORAGE) == -1 then
               return doPlayerSendCancel(cid, "There is not a poll in progress.")
           end
    
           if vote == -1 then
               return doPlayerSendCancel(cid, "You need to choose a option to vote.")
           end
    
           if getCreatureStorage(cid, PLAYER_STORAGE) == 1 then
                   print(getCreatureStorage(cid, PLAYER_STORAGE))
               return doPlayerSendCancel(cid, "You cannot vote two times.")
           end
    
           if vote > #options then
               return doPlayerSendDefaultCancel(cid, RETURNVALUE_NOTPOSSIBLE)
           end
    
           options[vote][2] = options[vote][2] + 1
           doSetStorage(OPTIONS_STORAGE, table.serialize(options))
           doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "You have voted in the option ".. options[vote][1] .." successfully!")
           doCreatureSetStorage(cid, PLAYER_STORAGE, 1)
       elseif(words == "/poll") then
           local options = table.unserialize(getStorage(OPTIONS_STORAGE))
           if getStorage(POLL_STORAGE) == -1 then
               return doPlayerSendCancel(cid, "There is not a poll in progress.")
           end
    
           local text = "ADVANCED poll SYSTEM\n\n".. getStorage(POLL_STORAGE) .."?\n"
           local count = 1
           for _, option in ipairs(options) do
               text = text .."\n#".. count .."   ".. option[1] .."   ".. (getTotalVotes() == 0 and 0 or math.floor((option[2]/getTotalVotes()) * 100)) .."%\n"
               count = count + 1
           end
           doPlayerPopupFYI(cid, text)
       elseif(words == "/endpoll") then
           if getStorage(POLL_STORAGE) == -1 then
               return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "There is not a poll to be ended.")
           end
    
           if not getMostVotedOption() then
               return doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Wait at least one vote to end this poll.")
           end
           local mostVotedOptions = getMostVotedOption()
           local mostVotedText = table.concat(mostVotedOptions, ", ")
           doBroadcastMessage("The poll '".. getStorage(POLL_STORAGE) .."?' has been finished!\nThe most voted option(s) was/were: ".. mostVotedText ..".")
           doSetStorage(POLL_STORAGE, -1)
           doSetStorage(OPTIONS_STORAGE, -1)
           for _, player in ipairs(getPlayersOnline()) do
               doCreatureSetStorage(player, PLAYER_STORAGE, -1)
           end
    
           db.executeQuery("UPDATE `player_storage` SET value = -1 WHERE `key` = ".. PLAYER_STORAGE ..";")
       end
       return true
    end

     

×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo