Ir para conteúdo
  • Cadastre-se

Action TFS 0.X Baú/Chest shop - Comprar mesmo item com 2 moedas diferentes


Posts Recomendados

  • Cat mudou o título para Baú/Chest shop - Comprar mesmo item com 2 moedas diferentes

Parabéns, seu tópico de conteúdo foi aprovado!
Muito obrigado pela sua contribuição, nós do Tibia King agradecemos.
Seu conteúdo com certeza ajudará à muitos outros, você recebeu +1 REP.

Spoiler

Congratulations, your content has been approved!
Thank you for your contribution, we of Tibia King we are grateful.
Your content will help many other users, you received +1 REP.

 

Link para o post
Compartilhar em outros sites

Muito bom!!

 

Porém tem um problema, se você remover o ITEM1 do jogador e ele não tiver o ITEM2, a compra não vai ter sucesso e ele irá sair lesado...

 

use a função "getPlayerItemCount (cid, itemid)" para saber se ele tem o item e a quantidade pedida!!

 

abraços

vodkart_logo.png

[*Ninguém será digno do sucesso se não usar suas derrotas para conquistá-lo.*]

 

DISCORDvodkart#6090

 

Link para o post
Compartilhar em outros sites
41 minutos atrás, Vodkart disse:

Muito bom!!

 

Porém tem um problema, se você remover o ITEM1 do jogador e ele não tiver o ITEM2, a compra não vai ter sucesso e ele irá sair lesado...

 

use a função "getPlayerItemCount (cid, itemid)" para saber se ele tem o item e a quantidade pedida!!

 

abraços

 

Não tinha percebido, obrigado por avisar.

 

Corrigido:

 

local coin = 2148  -- id da primeira moeda
local coin2 = 2160 -- id da segunda moeda
local eff = 28     -- efeito mágico ao comprar o item

local lever = {
[7017] = {50, 50, 10522} -- [actionid] = {quantidade da moeda 1, quantidade da moeda 2, id do item a comprar}
}

function onUse(cid,item,fromPosition,itemEx,toPosition)

if  getPlayerItemCount(cid, coin) >= (lever[item.actionid][1]) and getPlayerItemCount(cid, coin2) >= (lever[item.actionid][2]) then
	doPlayerRemoveItem(cid,coin,lever[item.actionid][1]) 
	doPlayerRemoveItem(cid,coin2,lever[item.actionid][2])
	
		doPlayerAddItem(cid,lever[item.actionid][3], isItemStackable(lever[item.actionid][3]) and 1)
		doPlayerSendTextMessage(cid,22,"Voce comprou " .. getItemNameById(lever[item.actionid][3]) .." por "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2))
		doSendMagicEffect(getCreaturePosition(cid), config.eff)

		else

    return doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "Sao necessarios "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2).. " para realizar esta compra.")
end
end

 

Editado por Daniel (veja o histórico de edições)
Link para o post
Compartilhar em outros sites
Em 01/06/2018 em 21:39, Nolis disse:

Vim disponibilizar esse código de chest que eu tava precisando e não achei em lugar algum.

Agradecimento ao @Sttorm que me ajudou a entender a estrutura do código.

 

 

Comprar mesmo item com 2 moedas diferentes! (Chest Action)

 

image.png.8a66662d4ab3045d603f135e770e21d4.png

23:31 Sao necessarios 50 gold coin e 50 crystal coin para realizar esta compra.

23:32 Voce comprou crown backpack por 50 gold coin e 50 crystal coin

 

 

data/actions/actions.xml: (mude baus/bau01.lua se o seu esquema for diferente)


<action actionid="6012" event="script" value="baus/bau01.lua"/>

 

data/actions/scripts/baus/bau01.lua: ( " )


local coin = 2148  -- id da primeira moeda
local coin2 = 2160 -- id da segunda moeda
local eff = 28     -- efeito mágico ao comprar o item

local lever = {
[7017] = {50, 50, 10522} -- [actionid] = {quantidade da moeda 1, quantidade da moeda 2, id do item a comprar}
}

function onUse(cid,item,fromPosition,itemEx,toPosition)

if  getPlayerItemCount(cid, coin) >= (lever[item.actionid][1]) and getPlayerItemCount(cid, coin2) >= (lever[item.actionid][2]) then
	doPlayerRemoveItem(cid,coin,lever[item.actionid][1]) 
	doPlayerRemoveItem(cid,coin2,lever[item.actionid][2])
	
		doPlayerAddItem(cid,lever[item.actionid][3], isItemStackable(lever[item.actionid][3]) and 1)
		doPlayerSendTextMessage(cid,22,"Voce comprou " .. getItemNameById(lever[item.actionid][3]) .." por "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2))
		doSendMagicEffect(getCreaturePosition(cid), config.eff)

		else

    return doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "Sao necessarios "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2).. " para realizar esta compra.")
end
end

 

versao..

8.54???

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

Sei que o tópico é antigo, mas curti a ideia e coloquei no meu baiak caso queiram pra tfs 1.x é assim.

Não entendo nada de script mas assim funcionou 100%

 

Spoiler

local coin = 2148  -- id da primeira moeda
local coin2 = 2160 -- id da segunda moeda


local lever = {
[7017] = {50, 50, 10522} -- [actionid] = {quantidade da moeda 1, quantidade da moeda 2, id do item a comprar}
}

function onUse(player,item,fromPosition,itemEx,toPosition)

if 	getPlayerItemCount(player, coin) >= (lever[item.actionid][1]) and getPlayerItemCount(player, coin2) >= (lever[item.actionid][2]) then
	doPlayerRemoveItem(player,coin,lever[item.actionid][1]) 
	doPlayerRemoveItem(player,coin2,lever[item.actionid][2])
	
		doPlayerAddItem(player,lever[item.actionid][3], isItemStackable(lever[item.actionid][3]) and 1)
		doPlayerSendTextMessage(player,22,"Voce comprou " .. getItemNameById(lever[item.actionid][3]) .." por "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2))
		player:getPosition():sendMagicEffect(5)

		else

    return doPlayerSendTextMessage(player, MESSAGE_INFO_DESCR, "Sao necessarios "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2).. " para realizar esta compra.")
end
end

 

 

Em lib\compat

Coloca no final essa função no final que funciona 100%

 

function getItemNameById(itemId) 
return ItemType(itemId):getName() 
end

Creditos pela função ao Zbizu da otland

Link para o post
Compartilhar em outros sites
  • 8 months later...
Em 01/06/2018 em 23:39, Cat disse:

Vim disponibilizar esse código de chest que eu tava precisando e não achei em lugar algum.

Agradecimento ao @Sttorm que me ajudou a entender a estrutura do código.

 

 

Comprar mesmo item com 2 moedas diferentes! (Chest Action)

 

image.png.8a66662d4ab3045d603f135e770e21d4.png

23:31 Sao necessarios 50 gold coin e 50 crystal coin para realizar esta compra.

23:32 Voce comprou crown backpack por 50 gold coin e 50 crystal coin

 

 

data/actions/actions.xml: (mude baus/bau01.lua se o seu esquema for diferente)


<action actionid="6012" event="script" value="baus/bau01.lua"/>

 

data/actions/scripts/baus/bau01.lua: ( " )


local coin = 2148  -- id da primeira moeda
local coin2 = 2160 -- id da segunda moeda
local eff = 28     -- efeito mágico ao comprar o item

local lever = {
[7017] = {50, 50, 10522} -- [actionid] = {quantidade da moeda 1, quantidade da moeda 2, id do item a comprar}
}

function onUse(cid,item,fromPosition,itemEx,toPosition)

if  getPlayerItemCount(cid, coin) >= (lever[item.actionid][1]) and getPlayerItemCount(cid, coin2) >= (lever[item.actionid][2]) then
	doPlayerRemoveItem(cid,coin,lever[item.actionid][1]) 
	doPlayerRemoveItem(cid,coin2,lever[item.actionid][2])
	
		doPlayerAddItem(cid,lever[item.actionid][3], isItemStackable(lever[item.actionid][3]) and 1)
		doPlayerSendTextMessage(cid,22,"Voce comprou " .. getItemNameById(lever[item.actionid][3]) .." por "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2))
		doSendMagicEffect(getCreaturePosition(cid), config.eff)

		else

    return doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "Sao necessarios "..lever[item.actionid][1].." " ..getItemNameById(coin).. " e "..lever[item.actionid][2].." " ..getItemNameById(coin2).. " para realizar esta compra.")
end
end

 

@Cat consegui  adaptar para tfs 1.2 versão 1098 ?

Link para o post
Compartilhar em outros sites

Participe da conversa

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

Visitante
Responder

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

  Apenas 75 emojis são permitidos.

×   Seu link foi automaticamente incorporado.   Mostrar como link

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

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

  • Quem Está Navegando   0 membros estão online

    Nenhum usuário registrado visualizando esta página.

  • Conteúdo Similar

    • Por Neutraz
      Advanced Roulette System (TFS 0.3.6)
       
      Hi everyone! This is my first contribution to the Tibia community, and I hope you find it very useful. It's a gacha-style roulette system with dynamic speed mechanics and multi-key functionality.
       
      What's it about?
      This script adds a roulette (Tested on: Tibia 8.6 -- TFS 0.3.6) where players can use keys to spin the roulette and win rewards. The system includes:
      Multi-key support: using 1 to 4 keys per spin, increasing the chances of winning. Dynamic speed: The roulette gradually accelerates during the spin to make it more exciting. Configurable rewards: You can define which items can be won and with what probability. You can even add "reroll" value to increase the difficulty! Visual effects: Includes simple effects and text animations to make the experience more engaging. Activity log: Keeps a record of which players won which items.  
      Demo Video (x1.5 Speed)
      Roulette2.mp4
       
       
      Installation
      Copy the `Roulette.lua` file to the `data/actions/scripts` folder of your TFS server. --[[ ================================================================================ = ROULETTE SYSTEM FOR TFS = = = = Author: Neutras = = Version: 2.1 = = Description: Gacha-style roulette system with dynamic speed mechanics = = and multi-key feature. = = = = Features: = = - Multi-key support (1-4 keys per spin). = = - Dynamic speed animation with configurable initial and final speeds. = = - Persistent "Winner Slot" effects and animated texts. = = - Configurable rewards with reroll chances. = = - Logging system to track player rewards. = = = = Compatible with TFS 0.3.7 (Tibia 8.6). = ================================================================================ --]] -- ================= LOGGING SYSTEM ================= -- local logPath = "data/logs/" local logFileName = "roulette.log" -- Logs player rewards to a file. -- @param cid: Player ID. -- @param keyName: Name of the key used. -- @param items: Table of items won. -- @param keyCount: Number of keys used. local function logEntry(cid, keyName, items, keyCount) local file = io.open(logPath .. logFileName, "a") if file then local itemStrings = {} for _, item in ipairs(items) do table.insert(itemStrings, string.format("x%d %s", item.count, getItemNameById(item.id))) end file:write(string.format("[%s] %s used %d '%s' and won: %s\n", os.date("%Y-%m-%d %H:%M:%S"), getPlayerName(cid), keyCount, keyName, table.concat(itemStrings, ", "))) file:close() end end -- ================= BASE CONFIGURATION ================= -- -- Levers Action IDs to key item IDs. local keyByAid = { [1354] = 9971, -- Key for reward level 1 (Copper) [1355] = 9972, -- Key for reward level 2 (Silver) [1356] = 9973 -- Key for reward level 3 (Golden) } -- Levers Action IDs to reward levels. local rewardByAid = { [1354] = 1, -- Reward level 1 (Copper) [1355] = 2, -- Reward level 2 (Silver) [1356] = 3 -- Reward level 3 (Golden) } -- Relative positions of the slots in the roulette. local rouletteSpinOffset = { {1, -4}, {2, -4}, {3, -4}, {3, -3}, {4, -3}, {4, -2}, {4, -1}, {5, -1}, {5, 0}, {5, 1}, {4, 1}, {4, 2}, {4, 3}, {3, 3}, {3, 4}, {2, 4}, {1, 4}, {0, 4}, {-1, 4}, {-2, 4}, {-3, 4}, {-3, 3}, {-4, 3}, {-4, 2}, {-4, 1}, {-5, 1}, {-5, 0}, {-5, -1},{-4, -1},{-4, -2}, {-4, -3},{-3, -3},{-3, -4},{-2, -4},{-1, -4}, {0, -4} } -- ================= MAIN CONFIGURATION ================= -- local config = { rouletteCD = 30, -- Global cooldown in seconds. globalStoCd = 22600, -- Storage ID for cooldown. globalStoKeyCount = 22601, -- Storage ID for key count. maxLoops = 100, -- Maximum iterations per spin. initialSpeed = 50, -- Initial speed in milliseconds. finalSpeed = 400, -- Final speed in milliseconds. effectLever = 35, -- Effect when activating the lever. effectRewardPlayer = 28, -- Effect on the player when winning. effectReward = 28, -- Effect on the winning slot. -- Reward table by level. -- Formula: Real Probability = (Item Chance / Total Chances) * (1 - (Reroll % / 100)) items = { [1] = { {id = 1, chance = 80, count = 5}, }, [2] = { {id = 2, chance = 70, count = 1, porc_cambio = 30}, }, [3] = { {id = 3, chance = 25, count = 1, porc_cambio = 70} } } } -- ================= PROBABILITY CACHING ================= -- -- Precalculates cumulative probabilities for each reward level. local cumulativeChanceCache = {} for rewardId, items in pairs(config.items) do local total = 0 local cumulative = {} for _, item in ipairs(items) do total = total + item.chance table.insert(cumulative, {item = item, threshold = total}) end cumulativeChanceCache[rewardId] = {total = total, items = cumulative} end -- ================= UTILITY FUNCTIONS ================= -- -- Calculates the speed of the roulette animation based on progress. -- @param progress: Current progress (0 to 1). -- @return: Speed in milliseconds. local function calculateSpeed(progress) return config.initialSpeed + (config.finalSpeed - config.initialSpeed) * progress^3 end -- Selects a random item from the reward table, considering reroll chances. -- @param rewardId: Reward level ID. -- @return: Selected item. local function chooseRouletteItem(rewardId) local cache = cumulativeChanceCache[rewardId] local roll = math.random(cache.total) for _, entry in ipairs(cache.items) do if roll <= entry.threshold then if entry.item.porc_cambio and math.random(100) <= entry.item.porc_cambio then return chooseRouletteItem(rewardId) end return entry.item end end return cache.items[#cache.items].item end -- Rotates the slots in the roulette. -- @param slots: Table of slots. local function rotateSlots(slots) local last = slots[36] for i = 36, 2, -1 do slots[i] = slots[i-1] end slots[1] = last end -- Updates the visual display of the roulette. -- @param cpos: Center position of the roulette. -- @param slots: Table of slots. -- @param isFillingPhase: Whether the slots are being filled for the first time. local function updateRouletteDisplay(cpos, slots, isFillingPhase) for i = 1, 36 do local pos = { x = cpos.x + rouletteSpinOffset[i][1], y = cpos.y + rouletteSpinOffset[i][2], z = cpos.z } doCleanTile(pos) if slots[i] then doCreateItem(slots[i].id, slots[i].count, pos) -- Show puff effect only during the initial filling phase. if isFillingPhase then doSendMagicEffect(pos, 14) end end end end -- ================= WINNER SLOTS AND EFFECTS ================= -- -- Shows "Winner Slot" animated text on winning slots. -- @param cpos: Center position of the roulette. -- @param keyCount: Number of keys used. local function showWinnerSlots(cpos, keyCount) local winningSlots = {} if keyCount == 1 then winningSlots = {36} elseif keyCount == 2 then winningSlots = {36, 18} elseif keyCount == 3 then winningSlots = {36, 18, 9} elseif keyCount == 4 then winningSlots = {36, 18, 9, 27} else winningSlots = {36} -- Default to one winning slot if keyCount is invalid. end for _, slot in ipairs(winningSlots) do local pos = { x = cpos.x + rouletteSpinOffset[slot][1], y = cpos.y + rouletteSpinOffset[slot][2], z = cpos.z } doSendAnimatedText(pos, "Winner Slot", TEXTCOLOR_YELLOW) end end -- Shows the number of keys in use. -- @param cpos: Center position of the roulette. local function showKeyCount(cpos) local keyCount = getGlobalStorageValue(config.globalStoKeyCount) keyCount = (keyCount < 1 or keyCount > 4) and 1 or keyCount local pos = {x = 1013, y = 995, z = 7} doSendAnimatedText(pos, string.format("Keys: %d", keyCount), TEXTCOLOR_LIGHTBLUE) end -- ================= MAIN ROULETTE LOGIC ================= -- -- Main animation function, recursively called to simulate the roulette spin. -- @param cid: Player ID. -- @param cpos: Center position of the roulette. -- @param rewardId: ID of the reward level. -- @param nloop: Current iteration number. -- @param slots: Table of slots (items). -- @param keyName: Name of the key used. -- @param keyCount: Number of keys used. local function shuffle(cid, cpos, rewardId, nloop, slots, keyName, keyCount) if nloop > config.maxLoops then if isPlayer(cid) then -- Determine winning slots based on the number of keys used. local winningSlots = {} if keyCount == 1 then winningSlots = {36} elseif keyCount == 2 then winningSlots = {36, 18} elseif keyCount == 3 then winningSlots = {36, 18, 9} elseif keyCount == 4 then winningSlots = {36, 18, 9, 27} else winningSlots = {36} -- Default to one winning slot if keyCount is invalid. end -- Get the winning items and their positions. local wonItems = {} local winPositions = {} for _, slot in ipairs(winningSlots) do if slots[slot] then table.insert(wonItems, slots[slot]) local pos = { x = cpos.x + rouletteSpinOffset[slot][1], y = cpos.y + rouletteSpinOffset[slot][2], z = cpos.z } table.insert(winPositions, pos) end end -- Award the items and display visual effects. if #wonItems > 0 then for _, pos in ipairs(winPositions) do doSendAnimatedText(pos, "Winner Slot", TEXTCOLOR_YELLOW) doSendMagicEffect(pos, config.effectReward) end for _, item in ipairs(wonItems) do doPlayerAddItem(cid, item.id, item.count) end doSendMagicEffect(getCreaturePosition(cid), config.effectRewardPlayer) -- Display a message to the player with all the rewards. local itemList = {} for _, item in ipairs(wonItems) do table.insert(itemList, string.format("x%d %s", item.count, getItemNameById(item.id))) end doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "[ROULETTE] You won: " .. table.concat(itemList, ", ")) -- Log the player's rewards. logEntry(cid, keyName, wonItems, keyCount) else doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "[ROULETTE] No items won.") end setGlobalStorageValue(config.globalStoCd, 0) end return end -- Initial filling phase of the roulette slots. if nloop <= 36 then slots[nloop] = chooseRouletteItem(rewardId) updateRouletteDisplay(cpos, slots, true) else -- Rotate the slots and update the display. rotateSlots(slots) updateRouletteDisplay(cpos, slots, false) -- Show effects on the winning slots every 5 iterations. if nloop % 5 == 0 then local winningSlots = {} if keyCount == 1 then winningSlots = {36} elseif keyCount == 2 then winningSlots = {36, 18} elseif keyCount == 3 then winningSlots = {36, 18, 9} elseif keyCount == 4 then winningSlots = {36, 18, 9, 27} else winningSlots = {36} -- Default to one winning slot if keyCount is invalid. end for _, slot in ipairs(winningSlots) do local pos = { x = cpos.x + rouletteSpinOffset[slot][1], y = cpos.y + rouletteSpinOffset[slot][2], z = cpos.z } doSendMagicEffect(pos, config.effectReward) end end end -- Schedule the next iteration with dynamic speed. local progress = nloop / config.maxLoops addEvent(shuffle, calculateSpeed(progress), cid, cpos, rewardId, nloop + 1, slots, keyName, keyCount) end -- ================= PERIODIC EFFECTS AND TEXTS ================= -- -- Shows effects and texts periodically. -- @param cpos: Center position of the roulette. local function showEffectsAndTexts(cpos) local keyCount = getGlobalStorageValue(config.globalStoKeyCount) keyCount = (keyCount < 1 or keyCount > 4) and 1 or keyCount -- Ensure keyCount is within range. -- Show "Winner Slot" on the winning slots. showWinnerSlots(cpos, keyCount) -- Show the number of keys in use. showKeyCount(cpos) -- Schedule the next execution. addEvent(showEffectsAndTexts, 1500, cpos) end -- ================= EFFECT SCRIPT INITIALIZATION ================= -- -- Start the periodic effects and texts when the script is loaded. local cpos = {x = 1012, y = 994, z = 7} -- Center position of the roulette. addEvent(function() showEffectsAndTexts(cpos) end, 5000) -- 5 seconds delay since server start. -- ================= MAIN OBJECT USE FUNCTION ================= -- -- Called when the roulette object is used. function onUse(cid, item, frompos, item2, topos) -- Handle the key change lever. if item.aid == 1360 then local current = getGlobalStorageValue(config.globalStoKeyCount) current = (current < 1 or current > 4) and 1 or (current % 4) + 1 setGlobalStorageValue(config.globalStoKeyCount, current) doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, string.format("Now using %d keys per spin.", current)) doSendMagicEffect(getThingPos(item.uid), CONST_ME_MAGIC_GREEN) return true end -- Handle the roulette levers. if not keyByAid[item.aid] then return false end local key = keyByAid[item.aid] local keyName = getItemNameById(key) local requiredKeys = getGlobalStorageValue(config.globalStoKeyCount) requiredKeys = (requiredKeys < 1 or requiredKeys > 4) and 1 or requiredKeys if getPlayerAccess(cid) < 5 and getPlayerItemCount(cid, key) < requiredKeys then doPlayerSendCancel(cid, string.format("You need %d %s to play!", requiredKeys, keyName)) doSendMagicEffect(topos, 14) return true end local rewardId = rewardByAid[item.aid] or 1 -- Get the reward level based on the lever. Default to 1 if not found. local pos = {x = 1012, y = 994, z = 7} -- Center position of the roulette. if getGlobalStorageValue(config.globalStoCd) > os.time() and getPlayerAccess(cid) < 5 then local remaining = getGlobalStorageValue(config.globalStoCd) - os.time() doPlayerSendCancel(cid, "Wait " .. remaining .. " seconds to play again.") return true end setGlobalStorageValue(config.globalStoCd, os.time() + config.rouletteCD) -- Set the cooldown. doTransformItem(item.uid, item.itemid == 9825 and 9826 or 9825) -- Change the lever's appearance. -- Clear the tiles around the roulette and add magic effects. for i = 1, 36 do local rpos = { x = pos.x + rouletteSpinOffset[i][1], y = pos.y + rouletteSpinOffset[i][2], z = pos.z } doCleanTile(rpos) doSendMagicEffect(rpos, config.effectReward) end if key > 0 then doPlayerRemoveItem(cid, key, requiredKeys) end -- Remove the keys from the player's inventory. doSendMagicEffect(pos, config.effectLever) -- Play the lever activation effect. math.randomseed(os.time() + getPlayerGUID(cid)) -- Seed the random number generator. addEvent(shuffle, config.initialSpeed, cid, pos, rewardId, 1, {}, keyName, requiredKeys) -- Start the roulette animation. return true end  
      Add the following lines within the `<actions>` tag in your `data/actions/actions.xml` file: <action actionid="XXX;YYYY;ZZZZ;AAAA" event="script" value="Roulette.lua"/> Replace `XXXX`, `YYYY`, and `ZZZZ` with the unique IDs of the levers that will activate the roulette (make sure they are not in use!).
      The ID `AAAA` is for the lever that changes the number of keys to use.
       
      Open the `Roulette.lua` file and adjust the `config.items` table with the items you want players to be able to win. Remember to balance the probabilities.  
       
      Code Explanation
      The script is divided into several sections to facilitate understanding:
      LOGGING SYSTEM: Handles logging the rewards obtained by players. BASE CONFIGURATION: Defines object IDs and reward levels. MAIN CONFIGURATION: Contains the main options of the system, such as the wait time between spins, the speed of the roulette, and the rewards. PROBABILITY CACHING: Optimizes the calculation of probabilities so that the system runs smoothly. UTILITY FUNCTIONS: Helper functions to calculate speed, choose items randomly, and update the roulette display. WINNER SLOTS AND EFFECTS: Displays the "Winner Slot" text and other visual effects in the winning spaces. MAIN ROULETTE LOGIC: The main function that controls the roulette animation and the delivery of rewards. PERIODIC EFFECTS AND TEXTS: Displays effects and texts periodically. SCRIPT INITIALIZATION: Initializes the effect system when the script is loaded. MAIN OBJECT USE FUNCTION: The function that is executed when a player interacts with a lever.

      I hope this roulette system is a great addition to your server! If you have any questions or suggestions, please feel free to leave a comment. Thank you for your support!  
       
    • Por L3K0T
      Se você está enfrentando o problema de jogadores ganhando experiência ao matar outros jogadores em um servidor PVP, e já tentou várias soluções sem sucesso, este tutorial vai te ajudar a resolver isso. A modificação que vou mostrar foi eficaz para mim e pode ser a solução para o seu servidor também.
       
      Passo 1: Acesse o arquivo creature.cpp
      Primeiro, abra o arquivo creature.cpp, que está localizado na pasta src ou sources do seu servidor. Esse arquivo contém a lógica das criaturas, incluindo a parte de quando um jogador mata outra criatura.
       
      Passo 2: Localize o  onAttackedCreatureKilled
      Dentro do arquivo, procure pela função onAttackedCreatureKilled:
       
      void Creature::onAttackedCreatureKilled(Creature* target) { if(target == this) return; double gainExp = target->getGainedExperience(this); onGainExperience(gainExp, !target->getPlayer(), false); }  
      Altere para
       
      void Creature::onAttackedCreatureKilled(Creature* target) { if (target == this) return; // Verifica se o atacante e o alvo são jogadores Player* attackerPlayer = this->getPlayer(); Player* targetPlayer = target->getPlayer(); if (attackerPlayer && targetPlayer) return; if (!attackerPlayer && targetPlayer) { double gainExp = target->getGainedExperience(this); onGainExperience(gainExp, !target->getPlayer(), false); } else if (attackerPlayer) { double gainExp = target->getGainedExperience(this); onGainExperience(gainExp, true, false); } }  
      Agora Recompile modo Rebuilder (LIMPA) e pronto!!!
       
      Aqui está o que mudou:
      *A primeira modificação verifica se o atacante e o alvo são jogadores. Se ambos forem jogadores, não será concedida experiência.
      *Se o atacante for um monstro, a experiência será concedida normalmente ao jogador.
      *Se o atacante for um jogador, ele ganhará a experiência normalmente.
       
      Créditos @L3K0T
    • Por Emooooo
      gostaria de um sistema em que o player usar um item nele, e quando ele bater no monstro ou outro player ele enchesse um pouco da mana e do life por porcentagem do dano causado, e com tempo de duração de duas horas depois tem que usar o item novamente.
      tfs 0.3.6
       
       
      +rep
    • Por L3K0T
      Sistema de Drop Personalizado
       
      Esse sistema de loot foi projetado para adicionar um elemento de sorte e surpresa ao derrotar monstros. Sempre que um jogador derrota um monstro, há uma chance configurada para que ele solte entre 1 a 3 itens especiais, garantindo recompensas valiosas ao jogador.
       
      O sistema realiza as seguintes ações:
      Chance de Drop: A cada morte de um monstro, há uma chance configurada para dropar itens específicos. O sistema permite que sejam dropados entre 1 a 3 unidades do item, tornando o sistema mais dinâmico.
       
      Efeito Visual: Quando o loot é bem-sucedido, um efeito visual especial (ID 231) é exibido na posição exata onde o monstro foi derrotado, criando uma animação visual que destaca a recompensa.
       
      Notificação ao Jogador: Após o drop, o jogador recebe uma mensagem personalizada informando a quantidade de itens obtidos. Essa notificação aparece após 3 segundos, adicionando uma camada de imersão e evitando sobrecarregar o chat imediatamente após a morte do monstro.
       
      *Ótimo para fazer eventos de dropar certo itens para alguma missão ou resgates.
      *Uso no meu TIBIA HARRY POTTER ORIGIN
       
      VAi em creaturescripts/scripts.lua
      local function findCorpse(position) for i = 1, 255 do position.stackpos = i local corpse = getThingfromPos(position) if isCorpse(corpse.uid) then return corpse.uid end end return false end local function dropLoot(position, killer) local corpse = findCorpse(position) if not corpse then return false end local itemId = 2160 local chance = 23 if math.random(100) <= chance then local amountToDrop = math.random(1, 3) doAddContainerItem(corpse, itemId, amountToDrop) local corpsePosition = getThingPos(corpse) doSendMagicEffect(corpsePosition, 7) local function sendMessage() if isPlayer(killer) then local message = string.format("Você dropou %d Crystal Coin(s).", amountToDrop) doPlayerSendTextMessage(killer, MESSAGE_INFO_DESCR, message) end end addEvent(sendMessage, 2500) end return true end function onKill(cid, target) local position = getCreaturePosition(target) addEvent(dropLoot, 100, position, cid) return true end  
      creaturescripts.xml
      <event type="kill" name="GlobalDrops" registerTo ="GlobalDrops" event="script" value="globalDrops.lua"/> ou depende do tfs
      <event type="kill" name="GlobalDrops" event="script" value="globalDrops.lua"/>  
      Para ambos TFS registra o evento no login.lua
      registerTo ="GlobalDrops"
      feito isso.. agora todos os monstros do mapa vai cair os crystal coins de 1 há 3.
    • Por L3K0T
      TUTORIAL BY L3K0T PT~EN
       
      Olá pessoal, trago a vocês uma atualização que fiz no sistema, contendo 3 novas funcionalidades de movimentação de itens e uma proteção contra Elf Bot. Estas adições foram cuidadosamente implementadas para aperfeiçoar a experiência de jogo e manter a integridade do seu servidor.
      As novas funcionalidades têm a função vital de impedir que jogadores deixem itens indesejados em locais inapropriados, como na entrada de sua casa, em cima de seus depósitos ou em teleportes. Agora, apenas proprietários, subproprietários e convidados têm permissão para manipular itens nesses locais.
      Este pacote de atualização foi meticulosamente revisado para evitar abusos por parte de jogadores mal-intencionados e garantir um ambiente de jogo justo e equilibrado para todos os usuários.
       
       
       
      Iniciando o Tutorial
      1Abra o arquivo "creatureevents.cpp" com o editor de sua preferência. Eu pessoalmente recomendo o Notepad++. 
       
       
      Em creatureevents.cpp:
      return "onPrepareDeath"; Adicione abaixo:
      case CREATURE_EVENT_MOVEITEM: return "onMoveItem"; case CREATURE_EVENT_MOVEITEM2: return "onMoveItem2";  
      Em:
      return "cid, deathList"; Adicione abaixo:
      case CREATURE_EVENT_MOVEITEM: return "moveItem, frompos, topos, cid"; case CREATURE_EVENT_MOVEITEM2: return "cid, item, count, toContainer, fromContainer, fromPos, toPos";  
      Em:
      m_type = CREATURE_EVENT_PREPAREDEATH; Adicione abaixo:
      else if(tmpStr == "moveitem") m_type = CREATURE_EVENT_MOVEITEM; else if(tmpStr == "moveitem2") m_type = CREATURE_EVENT_MOVEITEM2;  
      Procure por:
      bool CreatureEvents::playerLogout(Player* player, bool forceLogout) { //fire global event if is registered bool result = true; for(CreatureEventList::iterator it = m_creatureEvents.begin(); it != m_creatureEvents.end(); ++it) { if((*it)->getEventType() == CREATURE_EVENT_LOGOUT && (*it)->isLoaded() && !(*it)->executeLogout(player, forceLogout) && result) result = false; } return result; } Adicione abaixo:
      uint32_t CreatureEvents::executeMoveItems(Creature* actor, Item* item, const Position& frompos, const Position& pos) { // fire global event if is registered for(CreatureEventList::iterator it = m_creatureEvents.begin(); it != m_creatureEvents.end(); ++it) { if((*it)->getEventType() == CREATURE_EVENT_MOVEITEM) { if(!(*it)->executeMoveItem(actor, item, frompos, pos)) return 0; } } return 1; }  
      Em:
      bool CreatureEvents::playerLogin(Player* player) { //fire global event if is registered bool result = true; for(CreatureEventList::iterator it = m_creatureEvents.begin(); it != m_creatureEvents.end(); ++it) { if((*it)->getEventType() == CREATURE_EVENT_LOGIN && (*it)->isLoaded() && !(*it)->executeLogin(player) && result) result = false; } if (result) { for(CreatureEventList::iterator it = m_creatureEvents.begin(); it != m_creatureEvents.end(); ++it) { CreatureEvent* event = *it; if(event->isLoaded() && ( event->getRegister() == "player" || event->getRegister() == "all") ) player->registerCreatureEvent(event->getName()); } } return result; } Adicione Abaixo:
      uint32_t CreatureEvent::executeMoveItem(Creature* actor, Item* item, const Position& frompos, const Position& pos) { //onMoveItem(moveItem, frompos, position, cid) if(m_interface->reserveEnv()) { ScriptEnviroment* env = m_interface->getEnv(); if(m_scripted == EVENT_SCRIPT_BUFFER) { env->setRealPos(pos); std::stringstream scriptstream; env->streamThing(scriptstream, "moveItem", item, env->addThing(item)); env->streamPosition(scriptstream, "position", frompos, 0); env->streamPosition(scriptstream, "position", pos, 0); scriptstream << "local cid = " << env->addThing(actor) << std::endl; scriptstream << m_scriptData; bool result = true; if(m_interface->loadBuffer(scriptstream.str())) { lua_State* L = m_interface->getState(); result = m_interface->getGlobalBool(L, "_result", true); } m_interface->releaseEnv(); return result; } else { #ifdef __DEBUG_LUASCRIPTS__ char desc[35]; sprintf(desc, "%s", player->getName().c_str()); env->setEventDesc(desc); #endif env->setScriptId(m_scriptId, m_interface); env->setRealPos(pos); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); LuaInterface::pushThing(L, item, env->addThing(item)); LuaInterface::pushPosition(L, frompos, 0); LuaInterface::pushPosition(L, pos, 0); lua_pushnumber(L, env->addThing(actor)); bool result = m_interface->callFunction(4); m_interface->releaseEnv(); return result; } } else { std::clog << "[Error - CreatureEvent::executeMoveItem] Call stack overflow." << std::endl; return 0; } } uint32_t CreatureEvent::executeMoveItem2(Player* player, Item* item, uint8_t count, const Position& fromPos, const Position& toPos, Item* toContainer, Item* fromContainer, int16_t fstack) { //onMoveItem2(cid, item, count, toContainer, fromContainer, fromPos, toPos) if(m_interface->reserveEnv()) { ScriptEnviroment* env = m_interface->getEnv(); if(m_scripted == EVENT_SCRIPT_BUFFER) { env->setRealPos(player->getPosition()); std::stringstream scriptstream; scriptstream << "local cid = " << env->addThing(player) << std::endl; env->streamThing(scriptstream, "item", item, env->addThing(item)); scriptstream << "local count = " << count << std::endl; env->streamThing(scriptstream, "toContainer", toContainer, env->addThing(toContainer)); env->streamThing(scriptstream, "fromContainer", fromContainer, env->addThing(fromContainer)); env->streamPosition(scriptstream, "fromPos", fromPos, fstack); env->streamPosition(scriptstream, "toPos", toPos, 0); scriptstream << m_scriptData; bool result = true; if(m_interface->loadBuffer(scriptstream.str())) { lua_State* L = m_interface->getState(); result = m_interface->getGlobalBool(L, "_result", true); } m_interface->releaseEnv(); return result; } else { #ifdef __DEBUG_LUASCRIPTS__ char desc[30]; sprintf(desc, "%s", player->getName().c_str()); env->setEvent(desc); #endif env->setScriptId(m_scriptId, m_interface); env->setRealPos(player->getPosition()); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); lua_pushnumber(L, env->addThing(player)); LuaInterface::pushThing(L, item, env->addThing(item)); lua_pushnumber(L, count); LuaInterface::pushThing(L, toContainer, env->addThing(toContainer)); LuaInterface::pushThing(L, fromContainer, env->addThing(fromContainer)); LuaInterface::pushPosition(L, fromPos, fstack); LuaInterface::pushPosition(L, toPos, 0); //lua_pushnumber(L, env->addThing(actor)); bool result = m_interface->callFunction(7); m_interface->releaseEnv(); return result; } } else { std::clog << "[Error - CreatureEvent::executeMoveItem] Call stack overflow." << std::endl; return 0; } }  
       
       
      Agora em em creatureevents.h:
      CREATURE_EVENT_PREPAREDEATH, Adicione abaixo:
      CREATURE_EVENT_MOVEITEM, CREATURE_EVENT_MOVEITEM2  
      Em:
      uint32_t executePrepareDeath(Creature* creature, DeathList deathList); Adicione abaixo:
      uint32_t executeMoveItem(Creature* actor, Item* item, const Position& frompos, const Position& pos); uint32_t executeMoveItem2(Player* player, Item* item, uint8_t count, const Position& fromPos, const Position& toPos, Item* toContainer, Item* fromContainer, int16_t fstack);  
      Em:
      bool playerLogout(Player* player, bool forceLogout); Abaixo adicone também
      uint32_t executeMoveItems(Creature* actor, Item* item, const Position& frompos, const Position& pos); uint32_t executeMoveItem2(Player* player, Item* item, uint8_t count, const Position& fromPos, const Position& toPos, Item* toContainer, Item* fromContainer, int16_t fstack);  
       
      Agora em em game.cpp:
      if(!canThrowObjectTo(mapFromPos, mapToPos) && !player->hasCustomFlag(PlayerCustomFlag_CanThrowAnywhere)) { player->sendCancelMessage(RET_CANNOTTHROW); return false; } ReturnValue ret = internalMoveItem(player, fromCylinder, toCylinder, toIndex, item, count, NULL); if(ret == RET_NOERROR) return true; player->sendCancelMessage(ret); return false; } Altere para:
      if (!canThrowObjectTo(mapFromPos, mapToPos) && !player->hasCustomFlag(PlayerCustomFlag_CanThrowAnywhere)) { player->sendCancelMessage(RET_CANNOTTHROW); return false; } bool success = true; CreatureEventList moveitemEvents = player->getCreatureEvents(CREATURE_EVENT_MOVEITEM2); for (CreatureEventList::iterator it = moveitemEvents.begin(); it != moveitemEvents.end(); ++it) { Item* toContainer = toCylinder->getItem(); Item* fromContainer = fromCylinder->getItem(); if (!(*it)->executeMoveItem2(player, item, count, fromPos, toPos, (toContainer ? toContainer : 0), (fromContainer ? fromContainer : 0), fromStackpos) && success) success = false; } if (!success) return false; if (g_config.getBool(ConfigManager::ANTI_PUSH)) { std::string antiPushItems = g_config.getString(ConfigManager::ANTI_PUSH_ITEMS); IntegerVec tmpVec = vectorAtoi(explodeString(antiPushItems, ",")); if (tmpVec[0] != 0) { for (IntegerVec::iterator it = tmpVec.begin(); it != tmpVec.end(); ++it) { if (item->getID() == uint32_t(*it) && player->hasCondition(CONDITION_EXHAUST, 1)) { player->sendTextMessage(MSG_STATUS_SMALL, "Please wait a few seconds to move this item."); return false; } } } } int32_t delay = g_config.getNumber(ConfigManager::ANTI_PUSH_DELAY); if (Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_EXHAUST, delay, 0, false, 1)) player->addCondition(condition); if (!g_creatureEvents->executeMoveItems(player, item, mapFromPos, mapToPos)) return false; ReturnValue ret = internalMoveItem(player, fromCylinder, toCylinder, toIndex, item, count, NULL); if (ret != RET_NOERROR) { player->sendCancelMessage(ret); return false; } player->setNextAction(OTSYS_TIME() + g_config.getNumber(ConfigManager::ACTIONS_DELAY_INTERVAL) - 10); return true; }  
      Agora em configmanager.h
      ADMIN_ENCRYPTION_DATA Adicione abaixo:
      ANTI_PUSH_ITEMS,  
      em:
      STAMINA_DESTROY_LOOT, Adicione abaixo:
      ANTI_PUSH_DELAY,  
      em:
      ADDONS_PREMIUM, Adicione abaixo:
      ANTI_PUSH  
      Agora você pode compilar a Source.
       
       
      Configurando no servidor:
       
      Abra seu config.lua do servidor e adicione isso dentro qualquer lugar:
      -- Anti-Push useAntiPush = true antiPushItems = "2148,2152,2160,3976" antiPushDelay = 500  
       
      Navegue até o diretório 'creaturescripts' e localize o arquivo 'login.lua'.
      em resgistros de eventos adicione:
      login.lua
      registerCreatureEvent(cid, "MoveItem") registerCreatureEvent(cid, "MoveItem2")  
      Agora abra o aquivo creaturescript .xml
      <event type="moveitem" name="MoveItem" event="script" value="houseprotecao.lua"/> <event type="moveitem2" name="MoveItem2" event="script" value="moveitem2.lua"/>  
      Crie um novo arquivo lua em scripts com o nome houseprotecao.lua e adicione isso:
      function onMoveItem(moveItem, frompos, position, cid) if position.x == CONTAINER_POSITION then return true end local house = getHouseFromPos(frompos) or getHouseFromPos(position) --correção 100% if type(house) == "number" then local owner = getHouseOwner(house) if owner == 0 then return false, doPlayerSendCancel(cid, "Isso não é Possível.") end if owner ~= getPlayerGUID(cid) then local sub = getHouseAccessList(house, 0x101):explode("\n") local guest = getHouseAccessList(house, 0x100):explode("\n") local isInvited = false if (#sub > 0) and isInArray(sub, getCreatureName(cid)) then isInvited = true end if (#guest > 0) and isInArray(guest, getCreatureName(cid)) then isInvited = true end if not isInvited then return false, doPlayerSendCancel(cid, "Desculpe, você não está invitado.") end end end return true end  
      Crie um novo arquivo lua em scripts com o nome moveitem2.lua e adicione isso abaixo:
      local depottiles = {} --piso pra n jogar local depots = {2589} --id dos dps local group = 3 --id dos group 6 é todos. local function checkIfThrow(pos,topos) if topos.x == 0xffff then return false end local thing = getThingFromPos(pos) if isInArray(depottiles,thing.itemid) then if not isInArea(topos,{x=pos.x-1,y=pos.y-1,z=pos.z},{x=pos.x+1,y=pos.y+1, z=pos.z}) then return true end else for i = 1, #depots do if depots[i] == getTileItemById(topos,depots[i]).itemid or getTileInfo(topos).actionid == 7483 then return true end end end return false end function onMoveItem2(cid, item, count, toContainer, fromContainer, fromPos, toPos) if isPlayer(cid) then local pos = getThingPos(cid) if getPlayerGroupId(cid) > group then return true end if checkIfThrow({x=pos.x,y=pos.y,z=pos.z,stackpos=0},toPos) then doPlayerSendCancel(cid,"Não jogue item ai!!") doSendMagicEffect(getThingPos(cid),CONST_ME_POFF) return false end end return true end  
      ajudei?? REP+
      CRÉDITOS:
      @L3K0T
      Fir3element
      Summ
      Wise
      GOD Wille
      Yan Lima
       
       
       
       
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo