Ir para conteúdo
  • Cadastre-se

C++ AutoLoot Sources pra Otx2 (modificando o script do naze)


Posts Recomendados

  • 7 months later...
Em 30/03/2022 em 05:14, FeeTads disse:

salve rapaziada, do TK, esses tempos eu tava a procura de um autoloot bom e eficiente, e como vocês devem saber, o autoloot usado nos scripts .lua são bem "pesados"
o @Naze fez um excelentíssimo trabalho e disponibilizou um script de autoloot na source, porém como a vida é dificil, ele tem alguns bugs de função e um deles é no 
"remove autoloot" que quando o player digita "!autoloot remove, nome-do-item" nada acontece, eu decidi mexer e vim disponibilizar arrumado pra vcs.
LEMBRANDO QUE 100% DOS CRÉDITOS SÃO AO @Naze porém se vc procurar no tópico dele ainda vai estar bugado, então resolvi deixar aqui certinho pra ajudar quem precisar.


Link do tópico do naze: https://tibiaking.com/forums/topic/101086-otimizado-autoloot-in-sources-for-otx2-ou-menor/
 

  Ocultar conteúdo

Localize no arquivo "configmanager.h" os enum de string:
 



enum string_config_t
		{
			DUMMY_STR = 0,
			CONFIG_FILE,
			MAP_NAME,
			HOUSE_RENT_PERIOD,



E Adicione: 
 



enum string_config_t
		{
			AUTOLOOT_BLOCKIDS, //autoloot by naze#3578
			AUTOLOOT_MONEYIDS, //autoloot by naze#3578
			DUMMY_STR = 0,
			CONFIG_FILE,
			MAP_NAME,
			HOUSE_RENT_PERIOD,


No mesmo arquivo localize o enum de number:
 



enum number_config_t
		{
			LOGIN_TRIES = 0,
			RETRY_TIMEOUT,
			LOGIN_TIMEOUT,
			LOGIN_PORT,


E adicione:
 



enum number_config_t
		{
			AUTOLOOT_MAXITEM, //autoloot by naze#3578
			LOGIN_TRIES = 0,
			RETRY_TIMEOUT,
			LOGIN_TIMEOUT,
			LOGIN_PORT,



Localize no arquivo "configmanager.cpp" :
 



m_confString[MAP_AUTHOR] = getGlobalString("mapAuthor", "Unknown");
	m_confNumber[LOGIN_TRIES] = getGlobalNumber("loginTries", 3);



E adicione:

 



	m_confString[AUTOLOOT_BLOCKIDS] = getGlobalString("AutoLoot_BlockIDs", "");	//autoloot by naze#3578
	m_confString[AUTOLOOT_MONEYIDS] = getGlobalString("AutoLoot_MoneyIDs", "2148;2152;2160"); //autoloot by naze#3578
	m_confNumber[AUTOLOOT_MAXITEM] = getGlobalNumber("AutoLoot_MaxItem", 100); //autoloot by naze#3578
	m_confString[MAP_AUTHOR] = getGlobalString("mapAuthor", "Unknown");
	m_confNumber[LOGIN_TRIES] = getGlobalNumber("loginTries", 3);



Localize no arquivo "iologindata.cpp" :

 



//load storage map
	query.str("");
	query << "SELECT `key`, `value` FROM `player_storage` WHERE `player_id` = " << player->getGUID();
	if((result = db->storeQuery(query.str())))
	{
		do
			player->setStorage(result->getDataString("key"), result->getDataString("value"));
		while(result->next());
		result->free();
	}



E adicione a baixo :

 



	//load autoloot
	query.str("");
    query << "SELECT `autoloot_list` FROM `player_autoloot` WHERE `player_id` = " << player->getGUID();
    if ((result = db->storeQuery(query.str()))) {
        unsigned long lootListSize;
        const char* autoLootList = result->getDataStream("autoloot_list", lootListSize);
        // PropStream &propStream;
		PropStream propStream;
        propStream.init(autoLootList, lootListSize);

        uint16_t value;
        uint16_t item = propStream.getType<uint16_t>(value);
        while (item) {
            player->addAutoLoot(value);
            item = propStream.getType<uint16_t>(value);
        }
    }
	player->updateStatusAutoLoot(true);
	std::string msg = g_config.getString(ConfigManager::AUTOLOOT_MONEYIDS);
	StringVec strVector = explodeString(msg, ";");
	for(StringVec::iterator it = strVector.begin(); it != strVector.end(); ++it) {
		uint16_t id = atoi((*it).c_str());
		player->addAutoLoot(id);
	}


vai ficar da seguinte forma:
 

  Mostrar conteúdo oculto



//load storage map
	query.str("");
	query << "SELECT `key`, `value` FROM `player_storage` WHERE `player_id` = " << player->getGUID();
	if((result = db->storeQuery(query.str())))
	{
		do
			player->setStorage(result->getDataString("key"), result->getDataString("value"));
		while(result->next());
		result->free();
	}

	//load autoloot
	query.str("");
    query << "SELECT `autoloot_list` FROM `player_autoloot` WHERE `player_id` = " << player->getGUID();
    if ((result = db->storeQuery(query.str()))) {
        unsigned long lootListSize;
        const char* autoLootList = result->getDataStream("autoloot_list", lootListSize);
        // PropStream &propStream;
		PropStream propStream;
        propStream.init(autoLootList, lootListSize);

        uint16_t value;
        uint16_t item = propStream.getType<uint16_t>(value);
        while (item) {
            player->addAutoLoot(value);
            item = propStream.getType<uint16_t>(value);
        }
    }
	player->updateStatusAutoLoot(true);
	std::string msg = g_config.getString(ConfigManager::AUTOLOOT_MONEYIDS);
	StringVec strVector = explodeString(msg, ";");
	for(StringVec::iterator it = strVector.begin(); it != strVector.end(); ++it) {
		uint16_t id = atoi((*it).c_str());
		player->addAutoLoot(id);
	}



 


no mesmo arquivo localize:



query.str("");
	//save vip list
	if(!g_config.getBool(ConfigManager::VIPLIST_PER_PLAYER))
		query << "DELETE FROM `account_viplist` WHERE `account_id` = " << player->getAccount() << " AND `world_id` = " << g_config.getNumber(ConfigManager::WORLD_ID);
	else
		query << "DELETE FROM `player_viplist` WHERE `player_id` = " << player->getGUID();

	if(!db->query(query.str()))
		return false;


E Acima adicione:
 



//save autoloot
	query.str("");
	query << "DELETE FROM `player_autoloot` WHERE `player_id` = " << player->getGUID();
	if(!db->query(query.str()))
		return false;

	PropWriteStream PWS_AutoLoot;
	std::list<uint16_t> autoLootList = player->getAutoLoot();
    for (std::list<uint16_t>::iterator it = autoLootList.begin(); it != autoLootList.end(); ++it) {
		PWS_AutoLoot.addShort(*it);
    }

	uint32_t PWS_Size = 0;
	const char* autoLoot = PWS_AutoLoot.getStream(PWS_Size);

	query.str("");
	stmt.setQuery("INSERT INTO `player_autoloot` (`player_id`, `autoloot_list`) VALUES ");
    query << player->getGUID() << ',' << db->escapeBlob(autoLoot, PWS_Size);
    if (!stmt.addRow(query)) {
        return false;
    }
    if (!stmt.execute()) {
        return false;
    }

 

vai ficar da seguinte forma:

  Mostrar conteúdo oculto



/save autoloot
	query.str("");
	query << "DELETE FROM `player_autoloot` WHERE `player_id` = " << player->getGUID();
	if(!db->query(query.str()))
		return false;

	PropWriteStream PWS_AutoLoot;
	std::list<uint16_t> autoLootList = player->getAutoLoot();
    for (std::list<uint16_t>::iterator it = autoLootList.begin(); it != autoLootList.end(); ++it) {
		PWS_AutoLoot.addShort(*it);
    }

	uint32_t PWS_Size = 0;
	const char* autoLoot = PWS_AutoLoot.getStream(PWS_Size);

	query.str("");
	stmt.setQuery("INSERT INTO `player_autoloot` (`player_id`, `autoloot_list`) VALUES ");
    query << player->getGUID() << ',' << db->escapeBlob(autoLoot, PWS_Size);
    if (!stmt.addRow(query)) {
        return false;
    }
    if (!stmt.execute()) {
        return false;
    }
      
    query.str("");
	//save vip list
	if(!g_config.getBool(ConfigManager::VIPLIST_PER_PLAYER))
		query << "DELETE FROM `account_viplist` WHERE `account_id` = " << player->getAccount() << " AND `world_id` = " << g_config.getNumber(ConfigManager::WORLD_ID);
	else
		query << "DELETE FROM `player_viplist` WHERE `player_id` = " << player->getGUID();

	if(!db->query(query.str()))
		return false;

 

 

Agora no arquivo "monsters.cpp" localize toda a função "dropLoot" :  (ATENÇÃO: não confunda com "monster.cpp")
 



void MonsterType::dropLoot(Container* corpse)
{
	ItemList items;
	for(LootItems::const_iterator it = lootItems.begin(); it != lootItems.end() && !corpse->full(); ++it)
	{
		items = createLoot(*it);
		if(items.empty())
			continue;

		for(ItemList::iterator iit = items.begin(); iit != items.end(); ++iit)
		{
			Item* tmpItem = *iit;
			if(Container* container = tmpItem->getContainer())
			{
				if(createChildLoot(container, *it))
					corpse->__internalAddThing(tmpItem);
				else
					delete container;
			}
			else
				corpse->__internalAddThing(tmpItem);
		}
	}

	corpse->__startDecaying();
	uint32_t ownerId = corpse->getCorpseOwner();
	if(!ownerId)
		return;

	Player* owner = g_game.getPlayerByGuid(ownerId);
	if(!owner)
		return;

	LootMessage_t message = lootMessage;
	if(message == LOOTMSG_IGNORE)
		message = (LootMessage_t)g_config.getNumber(ConfigManager::LOOT_MESSAGE);

	if(message < LOOTMSG_PLAYER)
		return;

	std::stringstream ss;
	ss << "Loot of " << nameDescription << ": " << corpse->getContentDescription() << ".";
	if(owner->getParty() && message > LOOTMSG_PLAYER)
		owner->getParty()->broadcastMessage((MessageClasses)g_config.getNumber(ConfigManager::LOOT_MESSAGE_TYPE), ss.str());
	else if(message == LOOTMSG_PLAYER || message == LOOTMSG_BOTH)
		owner->sendTextMessage((MessageClasses)g_config.getNumber(ConfigManager::LOOT_MESSAGE_TYPE), ss.str());
}



e substitua com atenção ela toda por essa:

 



oid MonsterType::dropLoot(Container* corpse)
{	
	uint32_t money = 0;
	ItemList items;
	std::stringstream str;
	for(LootItems::const_iterator it = lootItems.begin(); it != lootItems.end() && !corpse->full(); ++it)
	{
		items = createLoot(*it);
		if(items.empty())
			continue;

		for(ItemList::iterator iit = items.begin(); iit != items.end(); ++iit)
		{
			Item* tmpItem = *iit;
			if(Container* container = tmpItem->getContainer())
			{
				Player* tmpPlayer = g_game.getPlayerByGuid(corpse->getCorpseOwner());
				if(createChildLoot(container, (*it), money, str, tmpPlayer)) {
					corpse->__internalAddThing(tmpItem);
				} else {
					delete container;
				}
			}
			else {
				bool LootCatch = false;
				Player* tmpPlayer = g_game.getPlayerByGuid(corpse->getCorpseOwner());
				if(tmpPlayer) {
					if(tmpPlayer->statusAutoLoot() == "On") {
						LootCatch = tmpPlayer->checkAutoLoot(tmpItem->getID());
						if(LootCatch) {
							if(tmpPlayer->isMoneyAutoLoot(tmpItem, money)) {
								continue;
							}
							g_game.internalPlayerAddItem(NULL, tmpPlayer, tmpItem);
							str << " " << tmpItem->getNameDescription() << ",";
							continue;
						}
					}
				}
				corpse->__internalAddThing(tmpItem);
			}
		}
	}

	corpse->__startDecaying();
	uint32_t ownerId = corpse->getCorpseOwner();
	if(!ownerId)
		return;

	Player* owner = g_game.getPlayerByGuid(ownerId);
	if(!owner)
		return;

	if(money != 0) {
		if(owner->statusAutoMoneyCollect() == "Bank"){
			owner->balance += money;
		} else {
			g_game.addMoney(owner, money);
		}
		str << " " << money << "x gold coins.";
	} else {
		str << " nothing gold coins.";
	}

	LootMessage_t message = lootMessage;
	if(message == LOOTMSG_IGNORE)
		message = (LootMessage_t)g_config.getNumber(ConfigManager::LOOT_MESSAGE);

	if(message < LOOTMSG_PLAYER)
		return;

	std::stringstream ss;
	ss << "Loot of " << nameDescription << ": " << corpse->getContentDescription() << ".";
	if(owner->statusAutoLoot()  == "On") {
		ss << "\nAutoLoot Colleted:" << str.str();
	}
	if(owner->getParty() && message > LOOTMSG_PLAYER)
		owner->getParty()->broadcastMessage((MessageClasses)g_config.getNumber(ConfigManager::LOOT_MESSAGE_TYPE), ss.str());
	else if(message == LOOTMSG_PLAYER || message == LOOTMSG_BOTH)
		owner->sendTextMessage((MessageClasses)g_config.getNumber(ConfigManager::LOOT_MESSAGE_TYPE), ss.str());
}



No mesmo arquivo localize a função a baixo chamada "createChildLoot": 
 



bool MonsterType::createChildLoot(Container* parent, const LootBlock& lootBlock)
{
	LootItems::const_iterator it = lootBlock.childLoot.begin();
	if(it == lootBlock.childLoot.end())
		return true;

	ItemList items;
	for(; it != lootBlock.childLoot.end() && !parent->full(); ++it)
	{
		items = createLoot(*it);
		if(items.empty())
			continue;

		for(ItemList::iterator iit = items.begin(); iit != items.end(); ++iit)
		{
			Item* tmpItem = *iit;
			if(Container* container = tmpItem->getContainer())
			{
				if(createChildLoot(container, *it))
					parent->__internalAddThing(tmpItem);
				else
					delete container;
			}
			else
				parent->__internalAddThing(tmpItem);
		}
	}

	return !parent->empty();
}


E substitua por essa:
 



bool MonsterType::createChildLoot(Container* parent, const LootBlock& lootBlock, uint32_t& money, std::stringstream& str, Player* player)
{
	LootItems::const_iterator it = lootBlock.childLoot.begin();
	if(it == lootBlock.childLoot.end())
		return true;

	ItemList items;
	for(; it != lootBlock.childLoot.end() && !parent->full(); ++it)
	{
		items = createLoot(*it);
		if(items.empty())
			continue;

		for(ItemList::iterator iit = items.begin(); iit != items.end(); ++iit)
		{
			Item* tmpItem = *iit;
			if(Container* container = tmpItem->getContainer())
			{
				if(createChildLoot(container, *it, money, str, player))
					parent->__internalAddThing(tmpItem);
				else
					delete container;
			}
			else {
				bool LootCatch = false;
				if(player && (player->statusAutoLoot() == "On")) {
					LootCatch = player->checkAutoLoot(tmpItem->getID());
				}
				if(LootCatch) {
					if(player->isMoneyAutoLoot(tmpItem, money)) {
						continue;
					}
					g_game.internalPlayerAddItem(NULL, player, tmpItem);
					str << " " << tmpItem->getNameDescription() << ",";
					continue;
				}
					parent->__internalAddThing(tmpItem);
			}
		}
	}

	return !parent->empty();
}


Agora no arquivo "monsters.h" altera apenas uma linha:

Encontre:



bool createChildLoot(Container* parent, const LootBlock& lootBlock);

e troque por:

 



bool createChildLoot(Container* parent, const LootBlock& lootBlock, uint32_t& money, std::stringstream& str, Player* player);


Agora no arquivo "player.h" encontre nas funções public:

 




		void learnInstantSpell(const std::string& name);
		void unlearnInstantSpell(const std::string& name);
		bool hasLearnedInstantSpell(const std::string& name) const;



E adicione abaixo:

 



//Autoloot by: Naze
		std::list<uint16_t> getAutoLoot() {
			return AutoLoot;
		}
		void clearAutoLoot() {
			AutoLoot.clear();
		}
		void addAutoLoot(uint16_t id);
		void removeAutoLoot(uint16_t id);
		bool limitAutoLoot();
		bool checkAutoLoot(uint16_t id);
		bool isMoneyAutoLoot(Item* item, uint32_t& count);
		std::string statusAutoLoot() {
			return (autoLootStatus ? "On" : "Off");
		}
		void updateStatusAutoLoot(bool status){
			autoLootStatus = status;
		}
		std::string statusAutoMoneyCollect() {
			return (autoMoneyCollect ? "Bank" : "Bag");
		}
		void updateMoneyCollect(bool status) {
			autoMoneyCollect = status;
		}


Localize no mesmo arquivo as declarações private: 

 



private:
		bool is_spectating;
		bool talkState[13];
		bool inventoryAbilities[SLOT_LAST];
		bool pzLocked;



e adicione 3 variáveis:

 



private:
		bool autoLootStatus; //autoloot by naze
		bool autoMoneyCollect; //autoloot by naze
		std::list<uint16_t> AutoLoot; //autoloot by naze
		bool is_spectating;
		bool talkState[13];
		bool inventoryAbilities[SLOT_LAST];
		bool pzLocked;



Agora no arquivo "player.cpp" localize no começo a função:

 



Player::Player(const std::string& _name, ProtocolGame* p):
	Creature(), transferContainer(ITEM_LOCKER), name(_name), nameDescription(_name), client(p)
{
	if(client)
		client->setPlayer(this);

	pzLocked = isConnecting = addAttackSkillPoint = requestedOutfit = false;
	saving = true;

	lastAttackBlockType = BLOCK_NONE;



e adicione: 

 



Player::Player(const std::string& _name, ProtocolGame* p):
	Creature(), transferContainer(ITEM_LOCKER), name(_name), nameDescription(_name), client(p)
{
	if(client)
		client->setPlayer(this);

	pzLocked = isConnecting = addAttackSkillPoint = requestedOutfit = false;
	saving = true;
	autoLootStatus = true; //autoloot by naze
	autoMoneyCollect = true; //autoloot by naze

	lastAttackBlockType = BLOCK_NONE;


Ainda em "player.cpp" vá até as ultimas função: 

 



void Player::sendCritical() const
{
	if(g_config.getBool(ConfigManager::DISPLAY_CRITICAL_HIT))
		g_game.addAnimatedText(getPosition(), COLOR_DARKRED, "CRITICAL!");
}

void Player::setPlayerExtraAttackSpeed(uint32_t speed)
{
	extraAttackSpeed = speed;
}



E adicione abaixo:



void Player::addAutoLoot(uint16_t id) {
	if(checkAutoLoot(id)) {
		return;
	}
	AutoLoot.push_back(id);
}

/*Parte do autoloot remove que foi arrumado*/
void Player::removeAutoLoot(uint16_t id) {
	if(!checkAutoLoot(id))
		return;
	
	for(std::list<uint16_t>::iterator it = AutoLoot.begin(); it != AutoLoot.end(); ++it) {
		if((*it) == id) {
		AutoLoot.erase(it); 
			break;
		}
	}	
}

bool Player::limitAutoLoot() {
	std::list<uint16_t> list = getAutoLoot();
	if((uint16_t)list.size() >= g_config.getNumber(ConfigManager::AUTOLOOT_MAXITEM)) {
		return true;
	}
	return false;
}

bool Player::checkAutoLoot(uint16_t id) {
	if(Item::items[id].isContainer()) {
		return true;
	}
	std::string msg = g_config.getString(ConfigManager::AUTOLOOT_BLOCKIDS);
	StringVec strVector = explodeString(msg, ";");
	for(StringVec::iterator it = strVector.begin(); it != strVector.end(); ++it) {
		if(atoi((*it).c_str()) == id) {
			return true;
		}
	}
	for(std::list<uint16_t>::iterator it = AutoLoot.begin(); it != AutoLoot.end(); ++it) {
		if((*it) == id) {
			return true;
		}
	}
	return false;
}

bool Player::isMoneyAutoLoot(Item* item, uint32_t& count) {
	bool isMoney = false;
	std::string msg = g_config.getString(ConfigManager::AUTOLOOT_MONEYIDS);
	StringVec strVector = explodeString(msg, ";");
	for(StringVec::iterator it = strVector.begin(); it != strVector.end(); ++it) {
		if(item->getID() == atoi((*it).c_str())) {
			isMoney = true;
			break;
		}
	}
	if(!isMoney) {
		return false;
    }
  
	count += item->getWorth();
	return true;
}



Agora quase finalizando no arquivo "talkactions.h" localize:
 



static TalkFunction diagnostics;
		static TalkFunction addSkill;
		static TalkFunction ghost;
		static TalkFunction software;


E adicione:




		static TalkFunction diagnostics;
		static TalkFunction addSkill;
		static TalkFunction autoLoot; //autoloot by naze
		static TalkFunction ghost;
		static TalkFunction software;


Encontre no arquivo "talkactions.cpp" :
 



else if(m_functionName == "diagnostics")
		m_function = diagnostics;
	else if(m_functionName == "addskill")
		m_function = addSkill;
	else if(m_functionName == "ghost")
		m_function = ghost;
	else if(m_functionName == "software")
		m_function = software;


E Adicione:



else if(m_functionName == "diagnostics")
		m_function = diagnostics;
	else if(m_functionName == "addskill")
		m_function = addSkill;	
	else if(m_functionName == "autoloot") //autoloot by naze
		m_function = autoLoot;	
	else if(m_functionName == "ghost")
		m_function = ghost;
	else if(m_functionName == "software")
		m_function = software;



Ainda em "talkactions.cpp" encontre o começo de ghost:



bool TalkAction::ghost(Creature* creature, const std::string&, const std::string&)
{
	Player* player = creature->getPlayer();
	if(!player)
		return false;



 E adicione a cima a seguinte função:
 



bool TalkAction::autoLoot(Creature* creature, const std::string&, const std::string& param)
{
	Player* player = creature->getPlayer();
	if(!player)
		return false;

	StringVec params = explodeString(param, ",");
	std::stringstream info;
	if(params[0] == "on" or params[0] == "off") {
		player->updateStatusAutoLoot((params[0] == "on" ? true : false));
		info << "Autoloot-> Status: " << (player->statusAutoLoot()) << ".";
		player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, info.str());
		return true;
	}
	if(params[0] == "clear" or params[0] == "clean") {
		player->clearAutoLoot();
		info << "Autoloot-> Todos itens removidos.";
		player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, info.str());
		return true;
	}
	if(params[0] == "list" or params[0] == "lista") {
		std::list<uint16_t> list = player->getAutoLoot();
		std::list<uint16_t>::iterator it = list.begin();
		std::string msg = g_config.getString(ConfigManager::AUTOLOOT_MONEYIDS);
		StringVec strVector = explodeString(msg, ";");
		for(StringVec::iterator itt = strVector.begin(); itt != strVector.end(); ++itt) {
			++it;
		}
		uint16_t i = 1;
		for(; it != list.end(); ++it) {	
			info << i << ": " << Item::items[(*it)].name << std::endl;
			++i;
		}
		player->sendFYIBox((info.str() == "" ? "Nada Adicionado." : info.str()));
		return true;
	}
	if(params.size() <= 1) {
		info << "_____Perfect AutoLoot System_____\nAutoLoot Status: " << player->statusAutoLoot() << "\nAutoMoney Mode: " << player->statusAutoMoneyCollect() << "\n\nComandos:\n!autoloot on/off\n!autoloot money, bank/bag\n!autoloot add, item name, item name, item name...\n!autoloot remove, item name, item name, item name...\n!autoloot list\n!autoloot clear\n\n\n (Sistema livre de bugs e gratuito no TibiaKing!)";
		player->sendFYIBox(info.str());
		return true;
	}

	if(params[0] == "money") {
		for(StringVec::iterator it = params.begin(); it != params.end(); ++it) {
			if((*it) == "money") {
				continue;
			}
			char param[150];
			sprintf(param, "%s", (*it).c_str());
			int len = strlen(param);
			for (int i = 0, pos = 0; i < len; i++, pos++) {
				if (param[0] == ' '){
					pos++;
				}
				param[i] = param[pos];
			}
			if((strcmp(param, "bank") == 0) or (strcmp(param, "bag") == 0)) {
				player->updateMoneyCollect((strcmp(param, "bank") == 0) ? true : false);
				info << "AutoMoney-> Collect Mode: " << (player->statusAutoMoneyCollect()) << ".";
				player->sendTextMessage(MSG_STATUS_CONSOLE_BLUE, info.str());
				return true;
			}
		}
	}

	if(params[0] == "add") {
		std::stringstream add, err;
		uint8_t addCount = 0, errCount = 0;
		std::stringstream ss;
		for(StringVec::iterator it = params.begin(); it != params.end(); ++it) {
			if((*it) == "add") {
				continue;
			}
			char name[150];
			sprintf(name, "%s", (*it).c_str());
			int len = strlen(name);
			for (int i = 0, pos = 0; i < len; i++, pos++) {
				if (name[0] == ' '){
					pos++;
				}
				name[i] = name[pos];
			}
			int32_t itemId = Item::items.getItemIdByName(name);
			if(!player->checkAutoLoot(itemId)) {
				if(itemId > 0) {
					std::string str = addCount > 0 ? ", " : "";
					++addCount;
					add << str << name;
					player->addAutoLoot(itemId);
					continue;
				}
			}
			std::string str = errCount > 0 ? ", " : "";
			++errCount;
			err << str << name;
		}
		ss << "AutoLoot-> Adicionados: " << ((add.str() == "") ? "Nenhum" : add.str()) << ". Erros: " << ((err.str() == "") ? "Nenhum" : err.str()) << ".";
		player->sendTextMessage(MSG_STATUS_CONSOLE_RED, ss.str());
		return true;
	}

	if(params[0] == "remove") {
		std::stringstream remove, err;
		uint8_t removeCount = 0, errCount = 0;
		std::stringstream ss;
		for(StringVec::iterator it = params.begin(); it != params.end(); ++it) {
			if((*it) == "remove") {
				continue;
			}
			char name[150];
			sprintf(name, "%s", (*it).c_str());
			int len = strlen(name);
			for (int i = 0, pos = 0; i < len; i++, pos++) {
				if (name[0] == ' '){
					pos++;
				}
				name[i] = name[pos];
			}
			int32_t itemId = Item::items.getItemIdByName(name);
			if(player->checkAutoLoot(itemId)) {
				if(itemId > 0) {
					std::string str = removeCount > 0 ? ", " : "";
					++removeCount;
					remove << str << name;
					player->removeAutoLoot(itemId);
					continue;
				}
			}
			std::string str = errCount > 0 ? ", " : "";
			++errCount;
			err << str << name;
		}
		ss << "AutoLoot-> Removidos: " << ((remove.str() == "") ? "Nenhum" : remove.str()) << ". Erros: " << ((err.str() == "") ? "Nenhum" : err.str()) << ".";
		player->sendTextMessage(MSG_STATUS_CONSOLE_ORANGE, ss.str());
		return true;
	}
	
	return true;
}



Com isso toda parte na source está instalada, agora vá até seu config.lua e adicione onde achar melhor as seguintes linhas:



AutoLoot_BlockIDs = "" -- adicione ids separado por ; ex: "1111;2222;3333"
AutoLoot_MoneyIDs = "2148;2152;2160" -- adicione os ids dos itens moeda, caso seja os 3 normais pode retirar essa linha
AutoLoot_MaxItem = 100 --  quantidade de itens maximo na lista


Agora para finalizar abra o data/talkactions/talkactions.xml e adicione a seguinte tag:



<talkaction words="/autoloot;!autoloot" event="function" value="autoloot"/>


E execute a seguinte query em seu banco de dados:



CREATE TABLE player_autoloot (
    id int NOT NULL AUTO_INCREMENT,
    player_id int NOT NULL,
    autoloot_list blob,
    PRIMARY KEY (id)
);


caso alguém ja utilize esse autoloot e esteja com o problema de remover items do autoloot
só ir em player.cpp e trocar

isso:
 


void Player::removeAutoLoot(uint16_t id) {
	if(checkAutoLoot(id)) {
		return;
	}
	AutoLoot.remove(id);
}


por isso:


void Player::removeAutoLoot(uint16_t id) {
	if(!checkAutoLoot(id))
		return;
	
	for(std::list<uint16_t>::iterator it = AutoLoot.begin(); it != AutoLoot.end(); ++it) {
		if((*it) == id) {
		AutoLoot.erase(it); 
			break;
		}
	}	
}


todos os créditos ao Naze, não sei se alguém mais fez esse código, mas como peguei do link citado acima que é post dele deixo aqui o autoloot 100% funcional direto nas sources

esse nao pega em tfs ne?

Link para o post
Compartilhar em outros sites
  • Moderador
1 hora atrás, mullino disse:

esse nao pega em tfs ne?

 

esse não me engano funciona em tfs 0.x e OTX 2.x, em TFS 1.x, creio que eh usado o sistema de quick loot veja aqui.
creio que esse autoloot funciona em qualquer TFS tbm, só testar, eh o mesmo do naze.

Link para o post
Compartilhar em outros sites
Agora, FeeTads disse:

 

esse não me engano funciona em tfs 0.x e OTX 2.x, em TFS 1.x, creio que eh usado o sistema de quick loot veja aqui.
creio que esse autoloot funciona em qualquer TFS tbm, só testar, eh o mesmo do naze.

The TFS Version: (1.2.X.SERIES -  a minha é essa

 

Link para o post
Compartilhar em outros sites
  • Moderador
3 minutos atrás, mullino disse:

The TFS Version: (1.2.X.SERIES -  a minha é essa

acho que funciona sim, tenta procurar as funções, ve se são parecidas, n custa tentar kkkkkk, mas creio que funciona sim.

Link para o post
Compartilhar em outros sites
  • 1 year later...

adicionei no meu otx 8.6 ultimo do github e esta 100% funcional, qualquer bug reporto !!

 

 

"Agora no arquivo "monsters.cpp" localize toda a função "dropLoot" :  (ATENÇÃO: não confunda com "monster.cpp")"

 

nessa parte do tutorial no codigo que esta escrito pra gente trocar está faltando o "V" no começo do codigo no "VOID" esta "OID" muita gente vai ter problema com isso.

 

 

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

Estejam atentos ao utilizar o sistema de autoloot, especialmente versões como a do Naze e outras similares, pois existem relatos de servidores sendo comprometidos através de ataques de estouro de buffer. Problemas como estes podem surgir devido ao uso da função sprintf e outras que não implementam mecanismos de segurança eficazes para controlar o tamanho do buffer. Mesmo definindo um limite de 150 caracteres, sprintf não realiza a verificação necessária para assegurar que o conteúdo gerado não ultrapasse esse limite. Ao declarar um buffer com char param[150], por exemplo, indica-se seu tamanho, mas sprintf não leva em consideração essa limitação, podendo resultar em escrita de dados além do espaço reservado se a string formatada superar 149 caracteres, ja que 1 caractere é reservado ao nulo 0

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 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
      Opa rapaziadaa beleza?
      Hoje estou disponibilizando uma source OTX 2, baseada na otx 2.x do mattyx - aqui, essa source que estou disponibilizando é um pouco diferente, com algumas features a mais do que a OTX padrão, como muitos sabem, a OTX serve apenas para abrir o seu OT, essa estou disponibilizando com algumas features, onde disponibilizei até scripts do TK, ou usando scripts do TK, tais como o autoloot na source do Naze, o projeto é pra Otserv 8.60. 
      Está sendo desenvolvido no github (projeto github) onde posto atualizações diárias do datapack e source. Vocês podem postar dúvidas, erros/bugs, dicas e qualquer outra coisa aqui no tópico ou no próprio github. Lembre-se de dar FOLLOW no projeto no github e SEGUIR o projeto aqui no fórum para acompanhar as atualizações.

      Edit
      systems Added:
      Max Absorb All: (protect SSA + Might Ring, você coloca o máximo de protect all que pode ser atingido, caso o player passe disso é ignorado, o maximo de protect vai ser o que está no config.lua)
      Commit max absorb all edit: fixed all system

      Delete Players With Monster Name: Deleta o player com nome de monstro, ou com nome proibido (alteravel pelo config.lua), caso vc deixe "deletePlayersWithMonsterName = false", irá apenas renomear o player aleatóriamente sem deleta-lo, ele não conseguirá logar com nome de monstro ou nome proibido.
      ps: Esse script pega o monster.xml todo, então mesmo que você adicione novos monstros, não precisar mexer em nada, ele ja vai pegar o novo monstro, mesmo sem precisar derrubar o Ot etc..
       
      deletePlayersWithMonsterName = true forbiddenNames = "gm;adm;cm;support;god;tutor;god ; god; adm;adm ; gm;gm ; cm;cm ;" --// other names here
      edit: 30/10
          modifyDamageInK = true   (essa função ativada irá modificar a saida do dano pra K, por exemplo 219000 > 219.0K / 2.000.000 > 2.00 KK).
          modifyExperienceInK = true  (esas função também mudará a saida normal pra K, isso é bom em high EXP pra arrumar aquela exp "-2147483647", de muita EXP, irá mudar pra "+2.14 Bi Exp").

      17/01 Last Changes:
      displayBroadcastLog = true - Desabilita os logs de broadcast do server na distro, aqueles logs de eventos etc... deixa a distro mais limpa. (by kizuno18)
      enableCriticalAndDodgeSource = true - (Sistema de Dodge E Critical de StatsChange pra source, deixa mais clean, mais leve, e o sistema pega em monstros, sem a necessidade de registrar o evento, previne bugs.)
      pushInProtectZone = false -   Sistema para desabilitar o push de player em PZ, impossibilitando que players empurrem outros players dentro do PZ.

      SpyCast: Sistema de SPY, pra GM+ ver a tela dos jogadores, como se eles estivessem de cast aberto, GM spy não mostra aviso nenhum que vc está monitorando o player, (sistema de telescope, se o player clicar no item com actionId configurado, mostra os players com cast on), Para GM+ mostra todos os players logados, independente se estão de cast on, para players mostra somente players com cast on.

      SendProgressbar: Sistema para feature do OTC, necessário saber usar e compilar o otcv8 com a modificação

      SetCreatureSpeed: Sistema usado pra setar a quantidade exata de speed de alguma criatura/player, usado no sistema de roleta (ainda não disponivel do datapack).

      (Projeto github)

      Informações:
      º  8.60
      º Baseado na OTX 2.x mattyx
      º Lib global (sistema pesadex)
      º Informações / changelog
      Dúvidas, erros, dicas e contribuições:
      Caso tenha dúvidas, ou queira resolver algum bug/erro, dar dicas para o projeto, ou também ajudar em sua construção, crie um issue / pull requests pelo github ou use esse tópico.


      Créditos:
      FeTads (FeeTads#0246) mattyx (source base e datapack) Reason182 (fixes e mais) Luxx (meu sócio de servidor, ajudou com teste) Daniel (spriter e dev junior) ADM Mario (cara brabo dos mapas e testes, achador de bug profissional) Luan Luciano (cara brabo que no inicio me ajudou d++)  
       
       
      Download:
       
      O download pode ser feito diretamente no github, ou clonando o projeto via git.
       
      How Compile:
      Windows Tutorial - Linux(Ubuntu) Tutorial

      Sistemas adicionado até o momento, todos 100% e sem bug.
       
       

    • 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