Ir para conteúdo
  • Cadastre-se

c++ [C++] TFS 1.2 / OTX Server 3 New Npc Currency System


Posts Recomendados

Sorry I don't speak spanish so you will have to bare with me.

 

This is a new way for people to create npc's which use different types of currency, rather than a coming up with different items to trade with the npc or trying to edit the npc modules this method simplifies everything by providing the npc with a npc currency id.

 

All this npc currency id is, is a storage value.. pretty simple eh?

If the npc doesn't have a currency id then it will use the normal currency e.g. gold, plat, cc etc..

 

I originally posted this on otland, but fuck them xD

 

Using Lailene here you can see she has a currency attribute with id of 123456

<?xml version="1.0" encoding="UTF-8"?>
<npc name="Lailene" currency="123456" script="lailene.lua" walkinterval="2000" floorchange="0" speechbubble="2">
<health now="100" max="100"/>
<look type="279" head="114" body="94" legs="113" feet="114" addons="0"/>
</npc>

 

Now any player who has a storage value of 123456 can purchase things from her shop provided they have enough value stored within the storage, similar to having money in the bank.

The money or in this case the storage value is added and removed from the player in real time.

 

Lets get to the code

 

game.cpp

Find this

bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)

Replace the whole function with this.

bool Game::removeMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)
{
    if (cylinder == nullptr) {
        return false;
    }

    if (money == 0) {
        return true;
    }
    uint32_t currencyId = 0;
    Player* player;
    if (Creature* creature = cylinder->getCreature()) {
        if (Player* p = creature->getPlayer()) {
            currencyId = p->getNpcCurrencyId();
            player = p;
        }
    }
    if (!currencyId) {
        std::vector<Container*> containers;

        std::multimap<uint32_t, Item*> moneyMap;
        uint64_t moneyCount = 0;

        for (size_t i = cylinder->getFirstIndex(), j = cylinder->getLastIndex(); i < j; ++i) {
            Thing* thing = cylinder->getThing(i);
            if (!thing) {
                continue;
            }

            Item* item = thing->getItem();
            if (!item) {
                continue;
            }

            Container* container = item->getContainer();
            if (container) {
                containers.push_back(container);
            }
            else {
                const uint32_t worth = item->getWorth();
                if (worth != 0) {
                    moneyCount += worth;
                    moneyMap.emplace(worth, item);
                }
            }
        }

        size_t i = 0;
        while (i < containers.size()) {
            Container* container = containers[i++];
            for (Item* item : container->getItemList()) {
                Container* tmpContainer = item->getContainer();
                if (tmpContainer) {
                    containers.push_back(tmpContainer);
                }
                else {
                    const uint32_t worth = item->getWorth();
                    if (worth != 0) {
                        moneyCount += worth;
                        moneyMap.emplace(worth, item);
                    }
                }
            }
        }

        if (moneyCount < money) {
            return false;
        }

        for (const auto& moneyEntry : moneyMap) {
            Item* item = moneyEntry.second;
            if (moneyEntry.first < money) {
                internalRemoveItem(item);
                money -= moneyEntry.first;
            }
            else if (moneyEntry.first > money) {
                const uint32_t worth = moneyEntry.first / item->getItemCount();
                const uint32_t removeCount = (money / worth) + 1;
                addMoney(cylinder, (worth * removeCount) - money, flags);
                internalRemoveItem(item, removeCount);
                break;
            }
            else {
                internalRemoveItem(item);
                break;
            }
        }
    }
    else {
        int32_t value;
        player->getStorageValue(currencyId, value);
        if (value < money) {
            return false;
        }
        player->addStorageValue(currencyId, value - money);
    }
    return true;
}

Next find this

void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)

Replace the whole function with this

void Game::addMoney(Cylinder* cylinder, uint64_t money, uint32_t flags /*= 0*/)
{
    if (money == 0) {
        return;
    }

    if (Creature* creature = cylinder->getCreature()) {
        if (Player* player = creature->getPlayer()) {
            if(uint32_t currencyId = player->getNpcCurrencyId()){
                int32_t value;
                player->getStorageValue(currencyId, value);
                player->addStorageValue(currencyId, value + money);
                return;
            }
        }
    }

    uint32_t crystalCoins = money / 10000;
    money -= crystalCoins * 10000;
    while (crystalCoins > 0) {
        const uint16_t count = std::min<uint32_t>(100, crystalCoins);

        Item* remaindItem = Item::CreateItem(ITEM_CRYSTAL_COIN, count);

        ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags);
        if (ret != RETURNVALUE_NOERROR) {
            internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT);
        }

        crystalCoins -= count;
    }

    uint16_t platinumCoins = money / 100;
    if (platinumCoins != 0) {
        Item* remaindItem = Item::CreateItem(ITEM_PLATINUM_COIN, platinumCoins);

        ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags);
        if (ret != RETURNVALUE_NOERROR) {
            internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT);
        }

        money -= platinumCoins * 100;
    }

    if (money != 0) {
        Item* remaindItem = Item::CreateItem(ITEM_GOLD_COIN, money);

        ReturnValue ret = internalAddItem(cylinder, remaindItem, INDEX_WHEREEVER, flags);
        if (ret != RETURNVALUE_NOERROR) {
            internalAddItem(cylinder->getTile(), remaindItem, INDEX_WHEREEVER, FLAG_NOLIMIT);
        }
    }

}

 

npc.cpp
Look for this

    pugi::xml_attribute attr;
    if ((attr = npcNode.attribute("speed"))) {
        baseSpeed = pugi::cast<uint32_t>(attr.value());
    } else {
        baseSpeed = 100;
    }

Right underneath that you are going to place this.

    if ((attr = npcNode.attribute("currency"))) {
        currency = pugi::cast<uint32_t>(attr.value());
    }

 

npc.h
Look for this

        bool isPushable() const final {
            return walkTicks > 0;
        }

Place this right underneath

        uint32_t getCurrencyId() const {
            return currency;
        }

Look for this

uint32_t walkTicks;

Place this right underneath

uint32_t currency;

 

player.cpp
Find this

void Player::openShopWindow(Npc* npc, const std::list<ShopInfo>& shop)

Replace that function with this

void Player::openShopWindow(Npc* npc, const std::list<ShopInfo>& shop)
{
    shopItemList = shop;
    sendShop(npc);
    sendSaleItemList(npc);
}

Next find this

bool Player::updateSaleShopList(const Item* item)

Replace that function with this

bool Player::updateSaleShopList(const Item* item)
{
    uint16_t itemId = item->getID();
    if (itemId != ITEM_GOLD_COIN && itemId != ITEM_PLATINUM_COIN && itemId != ITEM_CRYSTAL_COIN) {
        auto it = std::find_if(shopItemList.begin(), shopItemList.end(), [itemId](const ShopInfo& shopInfo) { return shopInfo.itemId == itemId && shopInfo.sellPrice != 0; });
        if (it == shopItemList.end()) {
            const Container* container = item->getContainer();
            if (!container) {
                return false;
            }

            const auto& items = container->getItemList();
            return std::any_of(items.begin(), items.end(), [this](const Item* containerItem) {
                return updateSaleShopList(containerItem);
            });
        }
    }

    if (client) {
        client->sendSaleItemList(shopOwner, shopItemList);
    }
    return true;
}

Next you are going to look for

uint64_t Player::getMoney() const

Now right underneath that function you are going to place these.

uint64_t Player::getMoney(Npc* npc) const
{
    uint64_t cash;
    setNpcCurrencyId(npc);
    uint32_t currencyId = getNpcCurrencyId();
    if (currencyId) {
        int32_t value;
        getStorageValue(currencyId, value);
        cash = (uint64_t)value;
    }
    else {
        cash = getMoney();
    }
    return cash;
}


void Player::setNpcCurrencyId(Npc* npc) const{
    currencyId = npc->getCurrencyId();
}

uint32_t Player::getNpcCurrencyId() const {
    return currencyId;
}

 

player.h
Look for this

        uint64_t getMoney() const;

Place this right underneath

        uint64_t getMoney(Npc*) const;

        void setNpcCurrencyId(Npc*) const;

        uint32_t getNpcCurrencyId() const;

Find this

        void sendShop(Npc* npc) const {
            if (client) {
                client->sendShop(npc, shopItemList);
            }
        }

Place this right underneath

        void sendSaleItemList(Npc* npc) const {
            if (client) {
                client->sendSaleItemList(npc, shopItemList);
            }
        }

Find this

        uint32_t manaMax;

Place this right underneath

         mutable uint32_t currencyId;

 

protocolgame.cpp

Now find this function

void ProtocolGame::sendSaleItemList(const std::list<ShopInfo>& shop)

Place this right underneath

void ProtocolGame::sendSaleItemList(Npc* npc, const std::list<ShopInfo>& shop)
{
    NetworkMessage msg;
    msg.addByte(0x7B);
    msg.add<uint64_t>(player->getMoney(npc));

    std::map<uint16_t, uint32_t> saleMap;

    if (shop.size() <= 5) {
        // For very small shops it's not worth it to create the complete map
        for (const ShopInfo& shopInfo : shop) {
            if (shopInfo.sellPrice == 0) {
                continue;
            }

            int8_t subtype = -1;

            const ItemType& itemType = Item::items[shopInfo.itemId];
            if (itemType.hasSubType() && !itemType.stackable) {
                subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType);
            }

            uint32_t count = player->getItemTypeCount(shopInfo.itemId, subtype);
            if (count > 0) {
                saleMap[shopInfo.itemId] = count;
            }
        }
    } else {
        // Large shop, it's better to get a cached map of all item counts and use it
        // We need a temporary map since the finished map should only contain items
        // available in the shop
        std::map<uint32_t, uint32_t> tempSaleMap;
        player->getAllItemTypeCount(tempSaleMap);

        // We must still check manually for the special items that require subtype matches
        // (That is, fluids such as potions etc., actually these items are very few since
        // health potions now use their own ID)
        for (const ShopInfo& shopInfo : shop) {
            if (shopInfo.sellPrice == 0) {
                continue;
            }

            int8_t subtype = -1;

            const ItemType& itemType = Item::items[shopInfo.itemId];
            if (itemType.hasSubType() && !itemType.stackable) {
                subtype = (shopInfo.subType == 0 ? -1 : shopInfo.subType);
            }

            if (subtype != -1) {
                uint32_t count;
                if (!itemType.isFluidContainer() && !itemType.isSplash()) {
                    count = player->getItemTypeCount(shopInfo.itemId, subtype); // This shop item requires extra checks
                } else {
                    count = subtype;
                }

                if (count > 0) {
                    saleMap[shopInfo.itemId] = count;
                }
            } else {
                std::map<uint32_t, uint32_t>::const_iterator findIt = tempSaleMap.find(shopInfo.itemId);
                if (findIt != tempSaleMap.end() && findIt->second > 0) {
                    saleMap[shopInfo.itemId] = findIt->second;
                }
            }
        }
    }

    uint8_t itemsToSend = std::min<size_t>(saleMap.size(), std::numeric_limits<uint8_t>::max());
    msg.addByte(itemsToSend);

    uint8_t i = 0;
    for (std::map<uint16_t, uint32_t>::const_iterator it = saleMap.begin(); i < itemsToSend; ++it, ++i) {
        msg.addItemId(it->first);
        msg.addByte(std::min<uint32_t>(it->second, std::numeric_limits<uint8_t>::max()));
    }

    writeToOutputBuffer(msg);
}

 

protocolgame.h

Find this

void sendSaleItemList(const std::list<ShopInfo>& shop);

Place this right underneath

void sendSaleItemList(Npc* npc, const std::list<ShopInfo>& shop);

 

luascript.cpp

Find

int LuaScriptInterface::luaPlayerAddMoney(lua_State* L)

Replace that whole function with this

int LuaScriptInterface::luaPlayerAddMoney(lua_State* L)
{
    // player:addMoney(money[, currencyId])
    uint64_t money = getNumber<uint64_t>(L, 2);
    uint32_t currencyId = getNumber<uint32_t>(L, 3);
    Player* player = getUserdata<Player>(L, 1);
    if (player) {
        if (currencyId) {
            int32_t value;
            player->getStorageValue(currencyId, value);
            player->addStorageValue(currencyId, value + money);
        }
        else {
            g_game.addMoney(player, money);
        }
        pushBoolean(L, true);
    } else {
        lua_pushnil(L);
    }
    return 1;
}

Next find this function which should be right below it.

int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L)

Replace that whole function with this

int LuaScriptInterface::luaPlayerRemoveMoney(lua_State* L)
{
    // player:removeMoney(money[, currencyId])
    Player* player = getUserdata<Player>(L, 1);
    if (player) {
        uint64_t money = getNumber<uint64_t>(L, 2);
        uint32_t currencyId = getNumber<uint32_t>(L, 3);
        if (currencyId) {
            int32_t value;
            player->getStorageValue(currencyId, value);
            if (value < money) {
                pushBoolean(L, false);
                return 1;
            }
            player->addStorageValue(currencyId, value - money);
            pushBoolean(L, true);
        }
        else {
            pushBoolean(L, g_game.removeMoney(player, money));
        }

    } else {
        lua_pushnil(L);
    }
    return 1;
}

 

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

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
  • 2 weeks later...

  @Codex NG  Hiho men if im using otx 2.x and i edit these sources files i will upgrade my otx 2 to 3 npc system?wait for u reply nice tuto

 

Link para o post
Compartilhar em outros sites
  • 4 weeks later...
On 10/18/2016 at 1:43 AM, Pastabase said:

  @Codex NG  Hiho men if im using otx 2.x and i edit these sources files i will upgrade my otx 2 to 3 npc system?wait for u reply nice tuto

 

If it works on otx2 then yes it will work on otx3, it also works on TFS 1.2/1.3

 

Some aspects of the sources haven't changed since 0.3, so you might even be able to use this code as far back as then of course you will need to make code adjustments. But i don't see why it can't be done.

Editado por Codex NG (veja o histórico de edições)
Link para o post
Compartilhar em outros sites
  • 1 year later...

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 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 Doria Louro
      Olá senhores.
       
      Gostaria de uma ajuda com um script de summon que venho trabalhando no momento, gostaria que o summon andasse do lado do jogador, entretanto o mesmo sempre fica para trás ou a frente do jogador.
      Efetuei a alteração na source creature.cpp:
       
      void Creature::getPathSearchParams(const Creature* creature, FindPathParams& fpp) const { fpp.fullPathSearch = !hasFollowPath; fpp.clearSight = true; if(creature->isPlayerSummon()) { if(creature->getName() == "Summon Name") fpp.clearSight = false; } fpp.maxSearchDist = 12; fpp.minTargetDist = fpp.maxTargetDist = 1; }  
      fpp.maxTargetDist = 1;
      Porém ele sempre mantem 1 de distancia do jogador, alterando para zero o "Zero" summon nem segue o jogador.
      Resultado:

       
      Agradeço desde já.
    • Por Imperius
      O propósito é criar uma nova função em creaturescripts que será acionada toda vez que um novo report (CTRL + R) for aberto.
       
      Eu implementei para enviar uma notificação no grupo do Telegram, contendo os dados do report.
       
      Isso garantirá que os GMs tenham acesso aos reports dos jogadores mesmo quando não estiverem logados, e também evitará que algum report seja perdido caso o jogador saia do servidor.
      A parte do Telegram é apenas um exemplo. Você pode ajustar o script para executar outras ações desejadas.
       
      creatureevent.cpp:
      Dentro deste arquivo, localize a função:
       
      uint32_t CreatureEvent::executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap)  
      abaixo dela, adicione:
       
      uint32_t CreatureEvent::executeOpenRuleViolation(Player* player, std::string message) { if (!m_interface->reserveEnv()) { std::clog << "[Error - CreatureEvent::executeOpenRuleViolation] Call stack overflow." << std::endl; return 0; } ScriptEnviroment* env = m_interface->getEnv(); env->setScriptId(m_scriptId, m_interface); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); lua_pushnumber(L, env->addThing(player)); lua_pushstring(L, message.c_str()); bool result = m_interface->callFunction(2); m_interface->releaseEnv(); return result; }  
      Após, procure por:
       
      std::string CreatureEvent::getScriptEventName() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "onLeaveChannel";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "onOpenRuleViolation";  
      Agora, procure por:
       
      std::string CreatureEvent::getScriptEventParams() const  
      abaixo de:
       
      case CREATURE_EVENT_CHANNEL_LEAVE: return "cid, channel, users";  
      adicione:
       
      case CREATURE_EVENT_OPEN_RULE_VIOLATION: return "cid, message";  
      Procure por:
       
      bool CreatureEvent::configureEvent(xmlNodePtr p)  
      abaixo de:
       
      else if(tmpStr == "leavechannel") m_type = CREATURE_EVENT_CHANNEL_LEAVE;  
      adicione:
       
      else if(tmpStr == "openruleviolation") m_type = CREATURE_EVENT_OPEN_RULE_VIOLATION;  
       
      creatureevent.h:
      Dentro deste arquivo, localize:
       
      enum CreatureEventType_t  
      adicione "CREATURE_EVENT_OPEN_RULE_VIOLATION" como o último item de enum CreatureEventType_t
       
      Exemplo:
       
      enum CreatureEventType_t { // ... CREATURE_EVENT_OPEN_RULE_VIOLATION };  
      Agora, procure por:
       
      uint32_t executeChannelLeave(Player* player, uint16_t channelId, UsersMap usersMap);  
      abaixo dela, adicione:
       
      uint32_t executeOpenRuleViolation(Player* player, std::string message);  
      game.cpp:
      Dentro deste arquivo, localize:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text)  
      e substitua por:
       
      bool Game::playerReportRuleViolation(Player* player, const std::string& text) { //Do not allow reports on multiclones worlds since reports are name-based if(g_config.getNumber(ConfigManager::ALLOW_CLONES)) { player->sendTextMessage(MSG_INFO_DESCR, "Rule violation reports are disabled."); return false; } cancelRuleViolation(player); boost::shared_ptr<RuleViolation> rvr(new RuleViolation(player, text, time(NULL))); ruleViolations[player->getID()] = rvr; ChatChannel* channel = g_chat.getChannelById(CHANNEL_RVR); if(!channel) return false; for(UsersMap::const_iterator it = channel->getUsers().begin(); it != channel->getUsers().end(); ++it) it->second->sendToChannel(player, SPEAK_RVR_CHANNEL, text, CHANNEL_RVR, rvr->time); CreatureEventList joinEvents = player->getCreatureEvents(CREATURE_EVENT_OPEN_RULE_VIOLATION); for(CreatureEventList::iterator it = joinEvents.begin(); it != joinEvents.end(); ++it) (*it)->executeOpenRuleViolation(player, text); return true; }  
      Agora é só compilar a source.
       
      depois em "data > creaturescripts > creaturescripts.xml", adicione:
       
      <event type="login" name="loginNotifyRuleViolation" script="notifyRuleViolation.lua"/> <event type="openruleviolation" name="openNotifyRuleViolation" script="notifyRuleViolation.lua"/>  
      em "data > creaturescripts > scripts", crie um arquivo notifyRuleViolation.lua e adicione:
       
      function onOpenRuleViolation(cid, message) local config = { token = "", -- Token do seu BOT no Telegram chatId = "" -- ID do chat do Telegram que será enviado a notificação. } local message = "Player: "..getCreatureName(cid).."\n\nReport:\n"..message.."" message = string.gsub(message, "\n", "%%0A") local url = "https://api.telegram.org/bot"..config.token.."/sendMessage" local data = "chat_id="..config.chatId.."&text="..message.."" local curl = io.popen('curl -d "'..data..'" "'..url..'"'):read("*a") return true end function onLogin(cid) registerCreatureEvent(cid, "openNotifyRuleViolation") return true end  
       
      Demonstração:
      1. Jogador abre um novo report (CTRL + R)

      2. notifyRuleViolation.lua, definido em creaturescripts.xml, é acionado para enviar uma notificação ao grupo do Telegram.
       

       
    • Por FeeTads
      SALVE rapaziada do TK, esses dias vim pensando em novos scripts pro meu OT, e em um deles eu precisava que determinada area não contasse frag pro player que matasse outros, PORÉM eu precisava que os players que morressem nessa area ainda assim tivessem as penalidades da sua morte, procurei por ai, achei alguns scripts que apenas tiravam o SKULL e não realmente o FRAG do player.

      **script atualizado 22/10/2023** - melhorado e otimizado, levei o script pra puxar as infos por .lua / creatureScripts

      vou disponibilizar o code aqui, e o que fazer pra determinada area não contar frag.

      SOURCE OTX 2 / TFS 0.x, Funciona em TFS 1.x mudando as tags e ajeitando as sintaxes.

      vá em creatureevent.cpp

      procure por:
      else if(type == "preparedeath") _type = CREATURE_EVENT_PREPAREDEATH;
      Adiciona abaixo:
      else if(type == "nocountfrag") _type = CREATURE_EVENT_NOCOUNTFRAG;

      procure por:
      case CREATURE_EVENT_PREPAREDEATH: return "onPrepareDeath";  
      Adicione abaixo: 
      case CREATURE_EVENT_NOCOUNTFRAG: return "noCountFragArea";

      procure por:
      case CREATURE_EVENT_PREPAREDEATH: return "cid, deathList";
      Adicione abaixo:
      case CREATURE_EVENT_NOCOUNTFRAG: return "cid, target";

      agora no mesmo arquivo, vá até o final do arquivo e adicione essa função:
      uint32_t CreatureEvent::executeNoCountFragArea(Creature* creature, Creature* target) { //noCountFragArea(cid, target) if(m_interface->reserveEnv()) { ScriptEnviroment* env = m_interface->getEnv(); if(m_scripted == EVENT_SCRIPT_BUFFER) { env->setRealPos(creature->getPosition()); std::ostringstream scriptstream; scriptstream << "local cid = " << env->addThing(creature) << std::endl; scriptstream << "local target = " << env->addThing(target) << std::endl; if(m_scriptData) 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__ std::ostringstream desc; desc << creature->getName(); env->setEvent(desc.str()); #endif env->setScriptId(m_scriptId, m_interface); env->setRealPos(creature->getPosition()); lua_State* L = m_interface->getState(); m_interface->pushFunction(m_scriptId); lua_pushnumber(L, env->addThing(creature)); lua_pushnumber(L, env->addThing(target)); bool result = m_interface->callFunction(2); m_interface->releaseEnv(); return result; } } else { std::clog << "[Error - CreatureEvent::noCountFragArea] Call stack overflow." << std::endl; return 0; } }

      agora vá em creatureevent.h

      procure por:
      CREATURE_EVENT_PREPAREDEATH
      adicione abaixo:
      CREATURE_EVENT_NOCOUNTFRAG

      procure por:
      uint32_t executePrepareDeath(Creature* creature, DeathList deathList);
      Adicione abaixo:
      uint32_t executeNoCountFragArea(Creature* creature, Creature* target);

      agora vá em player.cpp

      procure por:
      bool Player::onKilledCreature(Creature* target, DeathEntry& entry)
      abaixo de:
      War_t enemy; if(targetPlayer->getEnemy(this, enemy)) { if(entry.isLast()) IOGuild::getInstance()->updateWar(enemy); entry.setWar(enemy); }
      Adicione o seguinte código:
      if (targetPlayer){ CreatureEventList killEvents = getCreatureEvents(CREATURE_EVENT_NOCOUNTFRAG); for (const auto &event : killEvents) { if (!event->executeNoCountFragArea(this, target)) { return true; } } }

      //

      Feito isso, tudo completo na sua source, agora é necessário adicionar o creaturescript dentro do servidor

      vá até creaturescripts/scripts
      crie um arquivo chamado, "noCountFragInArea.lua"
      e dentro dele cole o código:
       
      --[[ script feito por feetads / TibiaKing ]]-- --[[ discord: feetads / FeeTads#0246 ]]-- -- Add positions here for which you do not want to count frags local areas = { [1] = {from = {x = 91, y = 122, z = 7}, to = {x = 98, y = 127, z = 7}}, -- from = area superior esquerda / to = area inferior direita (formando um quadrado) } local onlyKillerInArea = false -- only killer need to be in area? function noCountFragArea(cid, target) if not isCreature(cid) or not isCreature(target) then return true end local posKiller = getPlayerPosition(cid) local posTarget = getPlayerPosition(target) for i = 1, #areas do local area = areas[i] if isInArea(posKiller, area.from, area.to) then if onlyKillerInArea then return false elseif isInArea(posTarget, area.from, area.to) then return false end end end return true end
      agora em creaturescripts.xml
      <event type="nocountfrag" name="fragarea" event="script" value="noCountFragInArea.lua"/>
      agora em creaturescripts/scripts/login.lua
       procure por OU semelhante a esse:
      registerCreatureEvent(cid, "AdvanceSave")
      e abaixo adicione:
      registerCreatureEvent(cid, "fragarea")

      //


      Agora tudo certo, quando quiser adiciona uma area que não pega frag, vá até o script e apenas coloque a area, igual o demonstrado no script

      Exemplo:
      local areas = { [1] = {from = {x = 91, y = 122, z = 7}, to = {x = 98, y = 127, z = 7}}, [2] = {from = {x = 1000, y = 1000, z = 7}, to = {x = 1100, y = 1100, z = 7}}, }
      assim somente colocando a area no script e abrindo o server ou dando /reload, já funcionará a area como não pegar frag.
      Esse sistema pode ser bom pra areas de pvp ativo, onde você ainda quer que o player que morrer perca os atributos, como se fosse uma morte normal, porém não conta frag pra quem matar.
      Bom pra sistemas tipo castle 48h (guild war), onde há diversas mortes e risco de pegar red, atrapalhando a war.

      Façam bom proveito dos scripts, e deixem os créditos no script rsrs

      **Eu fiz as alterações e o simples código por isso vim disponibilizar, créditos meus**
    • Por Mateus Robeerto
      Para quem deseja utilizar o 'IncreaseMagicPercent' no arquivo items.xml, que aumenta o dano mágico em porcentagem
       
       
      No arquivo game.cpp
      depois.
      Player* attackerPlayer; if (attacker) { attackerPlayer = attacker->getPlayer(); } else { attackerPlayer = nullptr; } Player* targetPlayer = target->getPlayer(); if (attackerPlayer && targetPlayer && attackerPlayer->getSkull() == SKULL_BLACK && attackerPlayer->getSkullClient(targetPlayer) == SKULL_NONE) { return false; } damage.primary.value = std::abs(damage.primary.value); damage.secondary.value = std::abs(damage.secondary.value); int32_t healthChange = damage.primary.value + damage.secondary.value; if (healthChange == 0) { return true; } adicionar
      // Inc Magic by lursky auto originList = { ORIGIN_RANGED, ORIGIN_MELEE, ORIGIN_CONDITION }; auto it = std::find(originList.begin(), originList.end(), damage.origin); if (attackerPlayer && it == originList.end()) { int32_t magicPercentBonus = 0; for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { Item* item = attackerPlayer->inventory[slot]; if (item) { const ItemType& iiType = Item::items[item->getID()]; const int32_t& slotPosition = item->getSlotPosition(); if (iiType.increaseMagicPercent && (iiType.slotPosition & slotPosition)) { magicPercentBonus += iiType.increaseMagicPercent; } } } if (magicPercentBonus > 0) { damage.primary.value += damage.primary.value * (magicPercentBonus / 100.0f); } } No arquivo item.cpp
       
      post edit: Deve ter colocado duas vezes, ok? É só procurar no item.cpp essa linha e adicionar. Repita a busca pela mesma linha e adicione para exibir 'inc magic'. Pronto 

      depois.
      if (it.abilities) { for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; i++) { if (!it.abilities->skills[i]) { continue; } if (begin) { begin = false; s << " ("; } else { s << ", "; } s << getSkillName(i) << ' ' << std::showpos << it.abilities->skills[i] << std::noshowpos; } adicionar.
      if (it.increaseMagicPercent) { if (begin) { begin = false; s << " ("; } else { s << ", "; } s << "Inc.Magic " << std::showpos << it.increaseMagicPercent << '%' << std::noshowpos; } No arquivo items.cpp
      depois.
      {"worth", ITEM_PARSE_WORTH}, adicionar:
      { "increasemagicpercent", ITEM_PARSE_INCREASEMAGICPERCENT }, Novamente, no arquivo items.cpp:
      depois.
      case ITEM_PARSE_SUPPRESSCURSE: { if (valueAttribute.as_bool()) { abilities.conditionSuppressions |= CONDITION_CURSED; } break; } adicionar.
      case ITEM_PARSE_INCREASEMAGICPERCENT: { it.increaseMagicPercent = pugi::cast<int32_t>(valueAttribute.value()); break; } No arquivo items.h
      depois.
      uint64_t worth = 0; adicionar.
      int32_t increaseMagicPercent = 0; Novamente, no arquivo items.h:
      after.
      ITEM_PARSE_WORTH, adicionar:
      ITEM_PARSE_INCREASEMAGICPERCENT, FIM
      É só recompilar e testar
      Como funciona usar esses atributos? Veja aqui um exemplo
      item id="xxx" name="teste robe"> <attribute key="weight" value="7100"/> <attribute key="armor" value="18"/> <attribute key="slotType" value="body"/> <attribute key="increaseMagicPercent" value="50"/> </item>  
      Obs: Esses adições na source foram feitas por Mateus Roberto, e Lurskcy fez uma correção de erro que estava causando um .crash no arquivo games.cpp. Está funcionando bem.
       
      Espero que gostem
×
×
  • Criar Novo...

Informação Importante

Confirmação de Termo