Action TFS 0.X Mount System 1.4 - 100% Inovador!
-
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
Alterei a função canWalkthrough para Impedir o atravessamento de pisos específicos (como 11059 e 11060) se já houver um jogador sobre eles e assim ninguem entra no mesmo depot que é comum em pvp então vamos retirar isso.
Verificar o tipo de mundo (PVP / non-PVP / etc..) e zonas de proteção.
No PVP, jogadores podem atravessar se estiverem fora de uma zona de proteção ou quando ambos não estiverem em combate.
Segue as alterações:
vá em Player.cpp e ache:
bool Player::canWalkthrough(const Creature* creature) const { if(creature == this || hasFlag(PlayerFlag_CanPassThroughAllCreatures) || creature->isWalkable() || std::find(forceWalkthrough.begin(), forceWalkthrough.end(), creature->getID()) != forceWalkthrough.end() || (creature->getMaster() && creature->getMaster() != this && canWalkthrough(creature->getMaster()))) return true; const Player* player = creature->getPlayer(); if(!player) return false; if((((g_game.getWorldType() == WORLDTYPE_OPTIONAL && #ifdef __WAR_SYSTEM__ !player->isEnemy(this, true) && #endif player->getVocation()->isAttackable()) || player->getTile()->hasFlag(TILESTATE_PROTECTIONZONE) || (player->getVocation()->isAttackable() && player->getLevel() < (uint32_t)g_config.getNumber(ConfigManager::PROTECTION_LEVEL))) && player->getTile()->ground && Item::items[player->getTile()->ground->getID()].walkStack) && (!player->hasCustomFlag(PlayerCustomFlag_GamemasterPrivileges) || player->getAccess() <= getAccess())) return true; return (player->isGhost() && getGhostAccess() < player->getGhostAccess()) || (isGhost() && getGhostAccess() > player->getGhostAccess()); }
altere para
bool Player::canWalkthrough(const Creature* creature) const { if(creature == this || hasCustomFlag(PlayerCustomFlag_CanTurnhop) || creature->isWalkable() || (creature->getMaster() && creature->getMaster() != this && canWalkthrough(creature->getMaster()))) return true; const Player* player = creature->getPlayer(); if(!player) return false; const Tile* tile = player->getTile(); if(tile && tile->ground) { // Verifica se o tile e o chão existem uint16_t groundID = tile->ground->getID(); if(groundID == 11059 || groundID == 11060) { return false; // Bloqueia atravessamento para esses pisos } } if((((g_game.getWorldType() == WORLDTYPE_OPTIONAL && !player->isEnemy(this, true) && #ifdef __WAR_SYSTEM__ !player->isEnemy(this, true) && #endif player->getVocation()->isAttackable()) || player->getTile()->hasFlag(TILESTATE_PROTECTIONZONE) || (player->getVocation()->isAttackable() && player->getLevel() < (uint32_t)g_config.getNumber(ConfigManager::PROTECTION_LEVEL))) && player->getTile()->ground && Item::items[player->getTile()->ground->getID()].walkStack) && (!player->hasCustomFlag(PlayerCustomFlag_GamemasterPrivileges) || player->getAccess() <= getAccess())) return true; return (player->isGhost() && getGhostAccess() < player->getGhostAccess()) || (isGhost() && getGhostAccess() > player->getGhostAccess()); }
pronto só recompilar e testar.
-
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
-
Por Imperius
Olá, pessoal! Acabei encontrando um script que tinha feito a um tempo atrás. Estou compartilhando aqui para quem quiser usar ou melhorar.
É bem parecido com os outros sistemas de roleta, igual deste tópico: https://tibiaking.com/forums/topic/101557-action-cassino-roleta-de-items/
Como funciona?
O "Treasure Chest" é um item custom, onde o jogador têm a possibilidade de ganhar itens raros ou bem meia boca. Tudo dependerá da sorte.
O jogador precisa tacar o treasure chest na bancada e acionar a alavanca. O treasure chest irá se transformar em vários itens de forma randômica no qual o jogador poderá ou não ganhar. No final, apenas um item é entregue ao jogador.
Para entender melhor o seu funcionamento, segue o GIF abaixo:
em data > actions > actions.xml
em data > actions > scripts > crie um arquivo chamado leverTreasureChest.lua
no banco de dados do servidor, adicione o seguinte código em "SQL":
Também estou disponibilizando uma página PHP, para quem quiser usar no site do servidor. Na página tem informações sobre o funcionamento, quais são os possíveis prêmios e a lista de jogadores que ganharam os itens raros.
Espero ter ajudado de alguma forma! : )
treasure_chest.php
-
Por Dono do WNA
Andei procurando aqui pelo TK inteiro e não acho um script funcional para um boss room onde o player clica com direito num altar (parecido com uma alavanca) podendo ir sozinho ou com até 10 jogadores ele é teleportado para uma sala com o boss, podendo desafiar ele a cada 20 horas, toda vez que um jogador puxa a alavanca ele checa se tem player na sala e caso tenha, precisa esperar todos os jogadores sairem. Caso o boss esteja vivo sem players dentro da sala ele remove e adiciona um novo assim que puxam a alavanca.
Achei scripts parecidos no forum porém são todos para TFS 1.x+ e eu uso o 0.4 e nenhum compatível que achei esta funcionando
TFS 0.4 REV 3996
-
Posts Recomendados
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.