Ir para conteúdo

Featured Replies

Postado
  • Este é um post popular.

Para quem não sabe como funciona o evento : É um evento de defender a torre, no caso vão ter rodadas de monstros e as torres que você colocar vão atacar os monstros e os monstros vão ficando mais fortes a cada rodada e você claro também pode fazer upgrade em suas torres para não perder o evento.

Caso tenha alguma dúvida de como funciona o evento é só você procurar no Google por jogos de Tower Defense que são praticamente iguais ao evento.

 

OBS : Não me comprometo a dar suporte sobre instalação ou problemas perante aos scripts do evento/sistema, não sou dono do sistema estou apenas trazendo ao fórum com intuito de ajudar os membros que gostam de colocar eventos em seus servidores, qualquer dúvida ou problema você pode deixar ai em baixo mas coloque em mente que eu não estou me comprometendo a ajudar.

Evento desenvolvido por Printer com a ajuda de Limos e Ninja de outro fórum, todos os créditos do sistema vão para eles.

 

Características :

    

    Número ilimitado de rodadas pode ser configurado.

     • HP dos monstros, porcentagem de drop do gold e velocidade podem ser configurados.

     • Diferentes monstros, quantidades e espaço entre os monstros pode ser configurado.

     • Pode ser adicionado um número ilimitado de torres.

     • Preço das torres, upgrades, venda, cor e velocidade de ataque pode ser também fácilmente configurado no sistema.

     • Recompensas ao ganhar uma rodada também pode ser configurado.

Imagem :

UKQo4Ck.png

 

Adicionando o sistema

Como o tutorial é um pouco grande eu vou colocar em spoiler para não ficar um tópico muito grande.

 

Primeiramente abra "data/actions/actions.xml" e cole está linha :

<action itemid="2557" script="twdHammer.lua" allowfaruse="1"/>

Agora vá para "data/actions/scripts" e crie um arquivo lua com o nome "twdHammer" e cole este scripts dentro :

dofile('data/libs/TWD/towerDefenseLib.lua')

function onUse(player, item, fromPosition, target, toPosition, isHotkey)
    if player:getStorageValue(playingGameStorage) ~= 1 then
        return false
    end

    local tile = toPosition:getTile()
    if tile then
        if not tile:hasFlag(TILESTATE_PROTECTIONZONE) or tile:hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID) then
            player:sendCancelMessage("You cannot place the turret here.")
            return true
        end
    end

    if target:isItem() then
        local modalWindow = ModalWindow(100, "Build Turret", "Here you can select variations of turrets to build.")
        local turret, cfgTable = turrets.allTurretsId
        for i = 1, #turret do
            turret = turrets.allTurretsId[i]
            cfgTable = turrets[turret].cfg
            modalWindow:addChoice(turret, string.format("%s [%s coins]", cfgTable.turretName, cfgTable[1].buildPrice))
        end

        modalWindow:addButton(0, "Build")
        modalWindow:setDefaultEnterButton(0)
        modalWindow:addButton(1, "Cancel")
        modalWindow:setDefaultEscapeButton(1)
        modalWindow:sendToPlayer(player)
        turretPosition = toPosition
    elseif target:isNpc() and target:getName() == "Turret" then
        local table = turrets[target:getOutfit().lookType]
        local lvl = target:getTurretLevel()
        local cfg, cfgCombat = table.cfg[lvl], table.combat[lvl]

        local turrentInfo = string.format("Turret Information\n----------------------------\nTurret Level: %s\nAttack Type: %s\nRange SQM: %sx%s\nTurret Damage: [%s - %s]\nAttack Speed: %s\nSell/Upgrade Price: [%s / %s]", lvl, string.upper(cfgCombat.attackType), cfg.rangeX, cfg.rangeY, cfgCombat.dmgValues[1], cfgCombat.dmgValues[2], cfg.attackSpeed, cfg.sellPrice, cfg.upgradePrice)
        local playerInfo = string.format("Player Information\n----------------------------\nWave Level: %s\nYour Coins: %s", getWaveLevel(), player:getCoins())
        local modalWindow = ModalWindow(101, "Information", string.format("%s\n\n%s", turrentInfo, playerInfo))

        if lvl < 3 then
            modalWindow:addChoice(0, "Upgrade")
        end
        modalWindow:addChoice(1, "Sell")

        modalWindow:addButton(0, "Yes")
        modalWindow:setDefaultEnterButton(0)
        modalWindow:addButton(0x01, "Cancel")
        modalWindow:setDefaultEscapeButton(1)
        modalWindow:sendToPlayer(player)
        targetTurret = target
    end
    return true
end

Agora vá em "data/creaturescripts/creaturescripts.xml" e cole estas linhas :

    <event type="death" name="TWDDeath" script="twdEvent/twdDeath.lua"/>
    <event type="preparedeath" name="TWDOnLose" script="twdEvent/twdOnLose.lua"/>
    <event type="modalwindow" name="TWDBuildWindow" script="twdEvent/twdBuildWindow.lua"/>
    <event type="modalwindow" name="TWDOtherWindow" script="twdEvent/twdOtherWindow.lua"/>
    <event type="healthchange" name="TWDHealthChange" script="twdEvent/twdHealthChange.lua"/>

E agora em "data/creaturescripts/scripts" e crie uma pasta chamada twdEvent e dentro dela coloque os respectivos arquivos lua com seus respectivos nomes :

 

No arquivo lua com o nome "twdBuildWindow.lua" coloque o seguinte scripts :

dofile('data/libs/TWD/towerDefenseLib.lua')

function onModalWindow(player, modalWindowId, buttonId, choiceId)
    if modalWindowId ~= 100 then -- Not our window
             return false
       elseif buttonId == 1 then -- Cancel
             return false
       end

     local choice = turrets[choiceId]
       if not choice then
        return false
    end

    local table = choice.cfg[1]
    if player:getCoins() < choice.cfg[1].buildPrice then
        player:sendCancelMessage("You don't have enough of coins.")
        return false
    end

    local npc = Game.createNpc("Turret", turretPosition, false, true)
    if not npc then
        return false
    end

    player:addCoins(-choice.cfg[1].buildPrice)
    player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You have total ".. player:getCoins() .." coins.")

    local setColor = table.colorId
    npc:setOutfit({lookType = choiceId, lookHead = setColor , lookBody = setColor, lookLegs = setColor, lookFeet = setColor})
    npc:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE)
       return true
end

Crie outro com o nome "twdDeath.lua" e coloque este script dentro :

dofile('data/libs/TWD/towerDefenseLib.lua')

local function sendToNextWave(cid)
    local player = Player(cid)
    if not player then
        return false
    end

    local waveLevel = getWaveLevel()
    setWaveLevel(waveLevel + 1) -- Let's add + 1 to our current wave
    waveLevel = getWaveLevel() -- Let's refresh the variable

    if waveLevel <= waves.maxWaveLevel then -- Let's make sure there is more waves / Else end the event
        local waveTable = waves[waveLevel]
        player:sendTextMessage(MESSAGE_EVENT_ADVANCE, string.format("You have advanced to wave level %s, gained %s coins and %s experience points.", waveLevel, waveTable.goldBonus, waveTable.expBonus))
        startNextWave(waveLevel, twdConfig.startNextWaveTime)
        Game.setStorageValue(totalMonsterKillCountGlobalStorage, 0)
        player:addCoins(waveTable.goldBonus)
        player:addExperience(waveTable.expBonus, true)
        player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You have now total ".. player:getCoins() .." coins.")
    else
        sendReward(cid)
        resetEvent()
    end
end

function onDeath(creature, corpse, killer, mostDamageKiller, unjustified, mostDamageUnjustified)
    local player = getPlayerInEvent(20, 20)
    if not player then -- Make sure that the players exsist in the arena, to prevent errors
        return true
    end

    if killer and killer:isNpc() then
        local cfg = monsters[creature:getName()]
        creature:say("+" ..cfg.coins, TALKTYPE_MONSTER_SAY)
        player:addCoins(cfg.coins)
        player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You have total ".. player:getCoins() .." coins.")
    end

    Game.setStorageValue(totalMonsterKillCountGlobalStorage, Game.getStorageValue(totalMonsterKillCountGlobalStorage) + 1)
    if Game.getStorageValue(totalMonsterKillCountGlobalStorage) >= Game.getStorageValue(totalMonsterCountGlobalStorage) then
        sendToNextWave(player:getId())
    end
    return true
end

Outro com o nome "twdHealthChange.lua" e coloque este script :

function onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin)
    if primaryType == COMBAT_HEALING then
        return false
    end

    return primaryDamage, primaryType, secondaryDamage, secondaryType
end

Agora um com o nome "twdOnLose.lua" :

dofile('data/libs/TWD/towerDefenseLib.lua')


function onPrepareDeath(player, killer)
    if player:getStorageValue(playingGameStorage) ~= 1 then
        return true
    end

    player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "You have lost the Tower Of Defence Event.")
    player:resetValues()
    addEvent(resetEvent, twdConfig.resetEventTime * 1000)
    return false
end

twdOtherWindow.lua :

dofile('data/libs/TWD/towerDefenseLib.lua')

function onModalWindow(player, modalWindowId, buttonId, choiceId)
    if modalWindowId ~= 101 then -- Not our window
             return false
       elseif buttonId == 1 then -- Cancel
             return false
       end

    local npc = targetTurret
    local npcLvl = npc:getTurretLevel()
    local table = turrets[npc:getOutfit().lookType].cfg[npcLvl]

       if choiceId == 0 then
        if player:getCoins() < table.upgradePrice then
            player:sendCancelMessage("You don't have enough of coins.")
            return false
        end

        npcLvl = npcLvl + 1
        local setColor = table.colorId
        npc:setOutfit({lookType = npc:getOutfit().lookType, lookHead = setColor , lookBody = setColor, lookLegs = setColor, lookFeet = setColor, lookAddons = npcLvl})
        npc:getPosition():sendMagicEffect(math.random(CONST_ME_FIREWORK_YELLOW, CONST_ME_FIREWORK_BLUE))
        player:addCoins(-table.upgradePrice)
        player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You have total ".. player:getCoins() .." coins.")
        targetTurret = nil
    else
        player:addCoins(table.sellPrice)
        player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You have total ".. player:getCoins() .." coins.")
        npc:say("+" ..table.sellPrice, TALKTYPE_MONSTER_SAY)
        player:addCoins(table.sellPrice)
        npc:getPosition():sendMagicEffect(CONST_ME_MAGIC_RED)
        npc:remove()
        targetTurret = nil
    end
       return true
end

Pronto.

Agora crie uma pasta dentro da pasta "data/libs" do seu servidor com o nome de TWD, agora dentro da pasta TWD crie 3 arquivos lua com os respectivos nomes :

 

towerDefenseConfig.lua :

twdConfig = {
    loseHealth = 10, -- How much % should player lose, when the monster walk inside your base
    eventStartTime = 30, -- How long until the event starts, when player step in the teleport [seconds]
    startingCoins = 200, -- How much coins should the player start with!
    startNextWaveTime = 15, -- How long until next wave starts [seconds]
    resetEventTime = 10 -- How long until next player can enter, if someone already was in there [30 seconds] is recommended.
}

-- Write unused storage
playingGameStorage = 1000
coinStorage = 1001

-- Write unused global storage
waveLevelGlobalStorage = 100 -- Here write
totalMonsterCountGlobalStorage = 101
totalMonsterKillCountGlobalStorage = 102

-- Positions
eventRoomPosition = Position(1011, 1077, 7) -- Where should player get teleported in the event room?
eventCenterPosition = Position(1014, 1084, 7) -- Center of the event room
summonMonsterPosition = Position(1003, 1076, 7) -- Where should the monster be created?

turrets = {
    -- AttackTypes = target, aoe and targetAoe
    -- When you create new turret, make sure to write it's looktype in the [allTurretsId]

    allTurretsId = {129},
    [129] = { -- This Example of a target/aoe and targetAoe Turrent [Define by lookType]
        combat = {
            [1] = {attackType = "target", combatType = COMBAT_PHYSICALDAMAGE, combatArea = 0, dmgValues = {10, 20}, magicEffect = CONST_ME_NONE, shootEffect = CONST_ANI_ARROW},
            [2] = {attackType = "targetAoe", combatType = COMBAT_PHYSICALDAMAGE, combatArea = burstArrowArea, dmgValues = {30, 50}, magicEffect = CONST_ME_FIREAREA, shootEffect = CONST_ANI_BURSTARROW},
            [3] = {attackType = "aoe", combatType = COMBAT_PHYSICALDAMAGE, combatArea = AREA_CIRCLE2X2, dmgValues = {50, 70}, magicEffect = CONST_ME_GROUNDSHAKER, shootEffect = CONST_ANI_NONE}
        },
        cfg = {
            turretName = "Starter Turret",
            [1] = {buildPrice = 60, sellPrice = 30, upgradePrice = 120, rangeX = 3, rangeY = 3, colorId = 64, attackSpeed = 1000},
            [2] = {sellPrice = 60, upgradePrice = 180, rangeX = 4, rangeY = 4, colorId = 64, attackSpeed = 800},
            [3] = {sellPrice = 120, upgradePrice = 0, rangeX = 6, rangeY = 6, colorId = 64, attackSpeed = 500}
        }
    }
}

monsters = {-- monsterName, "drop" coins, current Health + extraHealth, speed
    ["Rat"] = {
        coins = 5,
        extraHealth = 0,
        speed = 400
    },
    ["Cave Rat"] = {
        coins = 5,
        extraHealth = 10,
        speed = 100
    }
}

waves = {
    maxWaveLevel = 3,
    [1] = {
            interval = 1000,
        goldBonus = 100,
        expBonus = 200,
        monsters = {
                        {name = "Rat", count = 10, interval = 500}
            }
    },
    [2] = {
            interval = 1000,
        goldBonus = 150,
        expBonus = 3000,
        monsters = {
                        {name = "Cave Rat", count = 10, interval = 500}
            }
    },
    [3] = {
            interval = 1000,
        goldBonus = 300,
        expBonus = 500,
        monsters = {
                        {name = "Rat", count = 10, interval = 500},
            {name = "Cave Rat", count = 10, interval = 500}
            }
    }
}

towerDefenseLib.lua :

	

    dofile('data/libs/TWD/towerDefenseSpellsArea.lua')
    dofile('data/libs/TWD/towerDefenseConfig.lua')
     
    targetTurret = nil
    turretPosition = nil
     
    local twdEvents = {
        "TWDOnLose",
        "TWDBuildWindow",
        "TWDOtherWindow",
        "TWDHealthChange"
    }
     
    function Player.resetValues(self)
        self:removeItem(2557, 1)
        self:setStorageValue(coinStorage, 0)
        self:addHealth(self:getMaxHealth())
        self:setStorageValue(playingGameStorage, 0)
        self:teleportTo(self:getTown():getTemplePosition())
        for i = 1, #twdEvents do
            self:unregisterEvent(twdEvents[i])
        end
    end
     
    function sendReward(cid)
        local player = Player(cid)
        player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "You have won the Tower Of Defense Event.")
        player:addItem(2160, 10)
        player:resetValues()
    end
     
    function resetEvent()
        turretPosition = nil
        targetTurret = nil
        setWaveLevel(0)
        Game.setStorageValue(totalMonsterKillCountGlobalStorage, 0)
        Game.setStorageValue(totalMonsterCountGlobalStorage, 0)
     
        local specs, turrets = Game.getSpectators(eventCenterPosition, false, false, 40, 40, 40, 40)
        for i = 1, #specs do
            turrets = specs[i]
            if turrets:isNpc() and turrets:getName() == "Turret" then
                turrets:remove()
            end
        end
    end
     
    -- Everytime the monster need to turn, you have to write the position of the turning point and where it should walk after it reached the point.
    local walkPaths = {
        Position(1003, 1076, 7),
        Position(1007, 1076, 7),
        Position(1007, 1085, 7),
        Position(998, 1085, 7),
        Position(998, 1091, 7),
        Position(1009, 1091, 7),
        Position(1009, 1096, 7),
        Position(1014, 1096, 7),
        Position(1014, 1091, 7),
        Position(1021, 1091, 7),
        Position(1021, 1079, 7),
        Position(1018, 1079, 7),
        Position(1018, 1075, 7)
    }
     
    local function monsterWalkTo(cid, fromPos, toPos, state) -- Limos
        local toPosState = toPos[state]
        if not toPosState then
            return false
        end
     
        if fromPos.y == toPosState.y then
            fromPos.x = fromPos.x > toPosState.x and fromPos.x - 1 or (fromPos.x < toPosState.x and fromPos.x + 1 or fromPos.x)
             else
            fromPos.y = fromPos.y > toPosState.y and fromPos.y - 1 or (fromPos.y < toPosState.y and fromPos.y + 1 or fromPos.y)
             end
     
        local monster = Monster(cid)
        if not monster then
            return false
        end
     
             monster:teleportTo(fromPos, true)
             if fromPos.x == toPosState.x and fromPos.y == toPosState.y then
                 state = state + 1
             end
     
        local speed = monsters[monster:getName()].speed
        if not speed then
            speed = 0
        end
     
             addEvent(monsterWalkTo, 1000 - speed, cid, fromPos, toPos, state)
    end
     
    function Npc.searchTarget(self, xRange, yRange)
        local target = self:getTarget()
        local specs, creatures = Game.getSpectators(self:getPosition(), false, false, xRange, xRange, yRange, yRange)
        for i = 1, #specs do
            if target then -- We already have a target, which is in range. Let's break the loop then
                break
            end
     
            creatures = specs[i]
            if creatures:isMonster() then -- Let's pick a target, which is a monster
                return self:setTarget(creatures)
            end
        end
    end
     
    function Npc.shootSpell(self, attackType, target, combat, area, min, max, magicEffect, distEffect)
        if attackType == "aoe" then
            doAreaCombatHealth(self, combat, self:getPosition(), area, -min, -max, magicEffect)
        elseif attackType == "targetAoe" then
            doAreaCombatHealth(self, combat, target:getPosition(), area, -min, -max, magicEffect)
            self:getPosition():sendDistanceEffect(target:getPosition(), distEffect)
        else
            doTargetCombatHealth(self, target, combat, -min, -max, magicEffect)
            self:getPosition():sendDistanceEffect(target:getPosition(), distEffect)
        end
    end
     
    function getPlayerInEvent(xRange, yRange)
        local player
        if player then
            return player
        end
     
        local specs = Game.getSpectators(eventCenterPosition, false, true, xRange, xRange, yRange, yRange)
        for i = 1, #specs do
            if specs[i]:getStorageValue(playingGameStorage) == 1 then
                player = specs[i]
                return player
            end
        end
    end
     
    local function summonMonster(name)
        local monster = Game.createMonster(name .."_TWD", summonMonsterPosition, false, true)
        if monster then
            monster:setDirection(EAST)
            monsterWalkTo(monster:getId(), monster:getPosition(), walkPaths, 1)
            summonMonsterPosition:sendMagicEffect(CONST_ME_TELEPORT)
            monster:changeSpeed(-monster:getSpeed() + 130)
     
            local extraHealth = monsters[name].extraHealth
            if extraHealth then
                monster:setMaxHealth(monster:getMaxHealth() + extraHealth)
                monster:addHealth(monster:getMaxHealth())
            end
        end
    end
     
    function startWaveLevel(level) -- Ninja
        local table, total = waves, 0
        for a = 1, #waves do
            table = waves[level]
            for b = 1, #table.monsters do
                for c = 1, table.monsters[b].count do
                    addEvent(function()
                        addEvent(summonMonster, b * table.monsters[b].interval, table.monsters[b].name)
                    end, c * table.interval)
                end
     
                total = total + table.monsters[b].count
            end
            break
        end
     
        Game.setStorageValue(totalMonsterCountGlobalStorage, total)
    end      
     
    function startNextWave(level, interval)
        addEvent(startWaveLevel, interval * 1000, level)
    end
     
    function Npc.setTurretLevel(self, level)
        if level > 3 then
            level = 3
        end
     
        local lookId = self:getOutfit().lookType
        local setColor = turrets[lookId].cfg[level].colorId
        self:setOutfit({lookType = lookId, lookHead = setColor , lookBody = setColor, lookLegs = setColor, lookFeet = setColor, lookAddons = level})
    end
     
    function Npc.getTurretLevel(self)
        local addon = self:getOutfit().lookAddons
        if addon == 0 then
            return 1
        end
     
        return addon
    end
     
    function getWaveLevel()
        return Game.getStorageValue(waveLevelGlobalStorage) or 0
    end
     
    function setWaveLevel(lvl)
        Game.setStorageValue(waveLevelGlobalStorage, lvl)
    end
     
    function Player.getCoins(self)
        return self:getStorageValue(coinStorage)
    end
     
    function Player.addCoins(self, amount)
        self:setStorageValue(coinStorage, math.max(0, self:getStorageValue(coinStorage)) + amount)
    end


towerDefenseSpellsArea.lua :

burstArrowArea = createCombatArea{ {1, 1, 1}, {1, 3, 1}, {1, 1, 1} }
AREA_CIRCLE2X2 = createCombatArea{
    {0, 1, 1, 1, 0},
    {1, 1, 1, 1, 1},
    {1, 1, 3, 1, 1},
    {1, 1, 1, 1, 1},
    {0, 1, 1, 1, 0}
}

Agora abra a pasta "data/movements/movements.xml" e coloque esta linha :

<movevent event="StepIn" fromuid="3333" touid="3334" script="twdTile.lua"/>

E dentro da pasta "data/movements/scripts" crie um arquivo lua com o nome "twdTile.lua" e coloque este scripts :

	

    dofile('data/libs/TWD/towerDefenseLib.lua')
     
    function onStepIn(creature, item, position, fromPosition)
            if item.uid == 3333 then
                    if not creature:isMonster() then
                            return false
                    end
     
                    local maxHealthDmg = creature:getMaxHealth()
                    doTargetCombatHealth(0, creature, COMBAT_PHYSICALDAMAGE, -maxHealthDmg, -maxHealthDmg, CONST_ME_FIREAREA)
     
                    local player = getPlayerInEvent(20, 20)
                    if not player then -- Make sure that the players exsist in the arena, to prevent errors
                            return true
                    end
     
                    local calcHealthDmg = (player:getMaxHealth() * twdConfig.loseHealth) / 100
                    doTargetCombatHealth(0, player:getId(), COMBAT_PHYSICALDAMAGE, -calcHealthDmg, -calcHealthDmg, CONST_ME_DRAWBLOOD)
            else
                    if not creature:isPlayer() then
                            return false
                    end
     
                    -- Let's make sure none is playing, before entrance
                    if getWaveLevel() > 0 then
                            creature:teleportTo(fromPosition, true)
                            fromPosition:sendMagicEffect(CONST_ME_TELEPORT)
                            creature:sendTextMessage(MESSAGE_INFO_DESCR, "There is someone already in the event.")
                            return true
                    end
     
                    -- Prepare Player
                    creature:teleportTo(eventRoomPosition)
                    creature:addHealth(creature:getMaxHealth())
                    creature:setStorageValue(playingGameStorage, 1)
                    creature:addCoins(twdConfig.startingCoins)
                    creature:addItem(2557, 1)
     
                    -- Setup Game
                    setWaveLevel(1)
                    startNextWave(1, twdConfig.eventStartTime)
                    Game.setStorageValue(totalMonsterKillCountGlobalStorage, 0)
     
                    -- Send Effects
                    eventRoomPosition:sendMagicEffect(CONST_ME_TELEPORT)
                    local pointingSummonPosition = summonMonsterPosition
                    Position(pointingSummonPosition.x + 1, pointingSummonPosition.y, pointingSummonPosition.z):sendMagicEffect(CONST_ME_TUTORIALARROW)
     
                    -- Send Messages
                    creature:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "You have total ".. creature:getCoins() .." coins.")
                    creature:sendTextMessage(MESSAGE_INFO_DESCR, "Welcome to the Tower Defense Event. The first wave will start in ".. twdConfig.eventStartTime .." seconds. Please build your first turret.")
                    creature:sendTextMessage(MESSAGE_STATUS_CONSOLE_ORANGE, "The blue arrow, points where the monsters are comming from. Use the hammer, to build your first turret.")
     
                    -- Register Events
                    creature:registerEvent("TWDOnLose")
                    creature:registerEvent("TWDHealthChange")
                    creature:registerEvent("TWDBuildWindow")
                    creature:registerEvent("TWDOtherWindow")
            end
            return true
    end


Agora vá em "data/monster/monster.xml" e coloque estas linhas :

    <!-- TWD Event -->
    <monster name="Rat_TWD" file="TWD Event/rat.xml"/>
    <monster name="Cave Rat_TWD" file="TWD Event/cave rat.xml"/>

E em "data/monster" crie uma pasta com o nome TWD Event e dentro da pasta coloque estes dois xml's :

 

cave rat.xml :

	

    <?xml version="1.0" encoding="UTF-8"?>
    <monster name="Cave Rat" nameDescription="a cave rat" race="blood" experience="0" speed="150" manacost="0">
            <health now="30" max="30"/>
            <look type="56" corpse="0"/>
            <targetchange interval="4000" chance="0"/>
            <flags>
                    <flag summonable="0"/>
                    <flag attackable="1"/>
                    <flag hostile="0"/>
                    <flag illusionable="1"/>
                    <flag convinceable="0"/>
                    <flag pushable="0"/>
                    <flag canpushitems="0"/>
                    <flag canpushcreatures="0"/>
                    <flag targetdistance="0"/>
                    <flag staticattack="90"/>
                    <flag runonhealth="0"/>
            </flags>s>
            <defenses armor="5" defense="5"/>
            <voices interval="5000" chance="10">
                    <voice sentence="Meeeeep!"/>
                    <voice sentence="Meep!"/>
            </voices>
            <script>
                    <event name="TWDDeath"/>
            </script>
    </monster>


rat.xml :

	

    <?xml version="1.0" encoding="UTF-8"?>
    <monster name="Rat" nameDescription="a rat" race="blood" experience="0" speed="135" manacost="0">
            <health now="20" max="20"/>
            <look type="21" corpse="0"/>
            <targetchange interval="4000" chance="0"/>
            <flags>
                    <flag summonable="0"/>
                    <flag attackable="1"/>
                    <flag hostile="1"/>
                    <flag illusionable="1"/>
                    <flag convinceable="0"/>
                    <flag pushable="0"/>
                    <flag canpushitems="0"/>
                    <flag canpushcreatures="0"/>
                    <flag targetdistance="0"/>
                    <flag staticattack="90"/>
                    <flag runonhealth="0"/>
            </flags>
            <defenses armor="5" defense="5"/>
            <voices interval="5000" chance="10">
                    <voice sentence="Meep!"/>
            </voices>
            <script>
                    <event name="TWDDeath"/>
            </script>
    </monster>


Agora vá em "data/npc" e crie um arquivo xml com o nome "Turret.xml" e cole este script :

<?xml version="1.0" encoding="UTF-8"?>
<npc name="Turret" script="Turret.lua" walkinterval="0" floorchange="0">
    <health now="100" max="100"/>
    <look type="129" head="57" body="59" legs="40" feet="76" addons="0"/>
</npc>

Agora dentro da pasta "data/npc/scripts" crie um arquivo lua com o nome "Turret.lua" e cole este script :

local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)

function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end

dofile('data/libs/TWD/towerDefenseLib.lua')  

local function searchForTarget(cid)
    local npc = Npc(cid)
    if not npc then
        return false
    end

    local lvl = npc:getTurretLevel()
    local table = turrets[npc:getOutfit().lookType]
    if not table then
        print("[ERROR]: This turret does not exsist in the turrets table.")
        return false
    end

    local cfg = table.cfg[lvl]
    npc:searchTarget(cfg.rangeX, cfg.rangeY)
    addEvent(searchForTarget, 100, cid)
end

local function onAttack(cid)
    local npc = Npc(cid)
    if not npc then
        return false
    end

    local lvl = npc:getTurretLevel()
    local table = turrets[npc:getOutfit().lookType]
    local cfg = table.cfg[lvl]

    if not table then
        print("[ERROR]: This turret does not exsist in the turrets table.")
        return false
    end

    local target = npc:getTarget()
    if target then
        local cfgCombat = table.combat[lvl]
        npc:shootSpell(cfgCombat.attackType, target, cfgCombat.combatType, cfgCombat.combatArea, cfgCombat.dmgValues[1], cfgCombat.dmgValues[2], cfgCombat.magicEffect, cfgCombat.shootEffect)
        npc:setFocus(target)
    end

    addEvent(onAttack, cfg.attackSpeed, cid)
end

function onCreatureAppear(creature)
    local cid = creature:getId()
    onAttack(cid)
    searchForTarget(cid)
    npcHandler:onCreatureAppear(creature)
end

 

 

Pronto, finalmente você terminou de instalar o script, agora basta baixar o mapa, colocar no seu servidor e se divertir !

E caso o evento seja bem avaliado pelos membros do TibiaKing eu me comprometo de traduzir ele para português para facilitar o entendimento dentro do game!

LINK para download do mapa : http://otland.net/attachments/twdmap-zip.28110/

 

Créditos : Printer, Limos, Ninja.

  • Respostas 8
  • Visualizações 3.4k
  • Created
  • Última resposta

Top Posters In This Topic

Most Popular Posts

  • Bem interessante, gostei da ideologia do evento em si. Dá pra gerar vários outros sistemas a partir desses códigos, com certeza contribuirá muito.   Não necessariamente, TFS 1.0 também executa

  • não funciona em TFS 1.0 ?

  • Cara você falou que pode ser adicionado torres mas eu tentei aqui e não é facil tem que mecher em muita cuida e mesmo assim da error consegue da uma mão ai?

Postado

Já tinha visto, e já testei o sistema ... é um evento até que interessante;

 

Obrigado por compartilhar com o fórum Viting :)

 

Qualquer erro só a glr postar que eu dou suporte nos scripts... lembrando que tem que se usar o novo TFS 1.1.

Postado

Bastante interessante ^^

Skype : wesleyyokrs              

 

 

 

 "Seja humilde, pois, até o sol com toda sua grandeza se põe e deixa a lua brilhar."

                        

-Eterno Poeta '

 

Postado

haha adorei a idéia. Nem sabia que já haviam feito algo assim...

Todos os meus trabalhos importantes estão na seção "Sobre mim" no meu perfil; Dá uma passada lá!

"Há três caminhos para o fracasso: não ensinar o que se sabe, não praticar o que se ensina, e não perguntar o que se ignora." - São Beda

I7Pm6ih.png

(obg ao @Beeny por fazer essa linda sign <3)

Postado

Bem interessante, gostei da ideologia do evento em si.
Dá pra gerar vários outros sistemas a partir desses códigos, com certeza contribuirá muito.



 

lembrando que tem que se usar o novo TFS 1.1.

Não necessariamente, TFS 1.0 também executa essas funções.
Só que nos códigos acima, o parâmetro referente ao creature ID (cid) foi definido para como sendo player, basta alterar ;]

The corrupt fear us.

The honest support us.

The heroic join us.

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

Quem Está Navegando 0

  • Nenhum usuário registrado visualizando esta página.

Estatísticas dos Fóruns

  • Tópicos 96.9k
  • Posts 519.6k

Informação Importante

Confirmação de Termo