class MerchantEnhancer(plugin: QuestIntelligence) {
private val pricing: YamlConfiguration = YamlConfiguration.loadConfiguration(File(plugin.dataFolder, "pricing.yml"))
private val items: MutableList<MutableMap<*, *>> = pricing.getMapList("items")
val professionItems: MutableMap<Profession, List<ItemStack>> = mutableMapOf()
init {
val professions = Lists.newArrayList(Registry.VILLAGER_PROFESSION).toTypedArray()
for (profession in professions) {
if (!plugin.config.contains("profession.$profession")) {
plugin.logger.warning("Профессия $profession отсутствует в конфигурации!")
continue
}
val lines = plugin.config.getStringList("profession.$profession.item-priority")
val itemList: MutableList<ItemStack> = lines.mapNotNull { line ->
val (materialName, amountStr) = line.split("~").let { it[0] to it[1] }
val amount = amountStr.toIntOrNull() ?: return@mapNotNull null
ItemStack(Material.valueOf(materialName), amount)
}.toMutableList()
professionItems[profession] = itemList
plugin.logger.info(profession.toString())
}
}
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
val itemPrice = calculateItemPrice(itemToBuy)
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
// Если житель не может заплатить за предмет, который он хочет
if (itemPrice > inventoryPrice)
return Transaction(true, mutableListOf(), itemPrice, inventoryPrice)
// Собираем предметы из инвентаря для будущей транзакции
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[merchant.profession].orEmpty().map { it.type }
for (item in inventory) {
// Пропускаем, если предмет из professionItems
if (professionExcludedItems.contains(item.type)) continue
// Если элемент имеет положительную цену
if (calculateItemPrice(item) > 0) {
barterItems.add(item)
}
// Проверяем, достаточно ли предметов для завершения обмена
if (calculateItemListPrice(barterItems) >= itemPrice) {
break // Достаточно предметов для завершения обмена
}
}
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
data class Transaction(val isCancelled: Boolean, val barterItems: List<ItemStack>, val itemPrice: Int, val villagerInventoryPrice: Int)
private fun calculateItemListPrice(itemList: List<ItemStack>): Int {
return itemList.sumOf { calculateItemPrice(it) }
}
private fun calculateInventoryPrice(inventory: Inventory): Int {
return inventory.sumOf { if (it != null) calculateItemPrice(it) else 0 }
}
private fun calculateItemPrice(item: ItemStack): Int {
return getMaterialPrice(item.type) * item.amount
}
private fun getMaterialPrice(material: Material): Int {
return items.find { it["name"] == material.name }
?.get("value") as? Int ?: 0 // Возвращает 0, если материал не найден
}
}
Assistant
Ваш код выглядит хорошо, но я могу предложить несколько улучшений для повышения читаемости и структурированности. Вот очищенный и немного упрощенный вариант вашего кода:
kotlin
User
Не забудь выравнить пробелы.
Assistant
Конечно! Привожу скорректированный код с правильным выравниванием пробелов:
kotlin
User
Мне нужно чтобы в первую очередь в собирались изумруды.
code
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
val itemPrice = calculateItemPrice(itemToBuy)
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
if (itemPrice > inventoryPrice) return Transaction(true, emptyList(), itemPrice, inventoryPrice)
val barterItems = this.gatherBarterItems(inventory, merchant.profession, itemPrice)
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
for (item in inventory) {
if (item == null || professionExcludedItems.contains(item.type) || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) >= itemPrice) {
break
}
}
return barterItems
}
Assistant
Чтобы модифицировать метод gatherBarterItems так, чтобы в первую очередь собирались изумруды, вы можете изменить логику сбора предметов. Сначала вы будете просматривать инвентарь и добавлять изумруды, а затем остальные предметы. Вот обновленный код:
kotlin
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
val itemPrice = calculateItemPrice(itemToBuy)
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
if (itemPrice > inventoryPrice) return Transaction(true, emptyList(), itemPrice, inventoryPrice)
val barterItems = gatherBarterItems(inventory, merchant.profession, itemPrice)
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
// Сначала собираем изумруды
for (item in inventory) {
if (item == null || professionExcludedItems.contains(item.type) || item.type != Material.EMERALD || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) >= itemPrice) {
break
}
}
// Если цена еще не достигнута, продолжаем собирать другие предметы
if (calculateItemListPrice(barterItems) < itemPrice) {
for (item in inventory) {
if (item == null || professionExcludedItems.contains(item.type) || item.type == Material.EMERALD || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) >= itemPrice) {
break
}
}
}
return barterItems
}
Объяснение изменений:
Первый цикл: Мы перебираем инвентарь и сначала собираем только изумруды (предмет с типом Material.EMERALD).
Проверка цены: После первого цикла, если цена еще не достигнута, мы переходим ко второму циклу.
Второй цикл: Собираем остальные предметы, пропуская при этом уже собранные изумруды.
Таким образом, эта модификация гарантирует, что изумруды будут собираться в первую очередь, что соответствует вашим требованиям.
User
Ты не понял. Изумруды тоже имеют свою цену. Мне нужно чтобы в первую очередь подсчитывалась цена изумрудов, если они конечно есть в инвентаре.
Assistant
Понял вас. В таком случае, вам нужно изменить логику метода gatherBarterItems так, чтобы он сначала проверял количество изумрудов в инвентаре и учитывал их стоимость в расчете общей суммы, необходимой для транзакции. Если их достаточно, вы добавляете их к barterItems.
Вот обновленный метод gatherBarterItems, который сначала подсчитывает стоимость изумрудов и использует их для завершения транзакции, прежде чем рассматривать другие предметы:
kotlin
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
// Переменная для хранения стоимости изумрудов
var emeraldsValue = 0
// Сначала собираем изумруды и рассчитываем их общую стоимость
for (item in inventory) {
if (item == null || professionExcludedItems.contains(item.type) || calculateItemPrice(item) <= 0) continue
if (item.type == Material.EMERALD) {
emeraldsValue += calculateItemPrice(item) // Добавляем стоимость изумрудов
barterItems.add(item) // Добавляем изумруды в список
}
}
// Проверяем, хватает ли стоимости изумрудов для выполнения транзакции
if (emeraldsValue >= itemPrice) {
// Если стоимость изумрудов достаточна, можем завершить транзакцию
return barterItems
}
// Если стоимость изумрудов не хватает, продолжаем собирать другие предметы
for (item in inventory) {
if (item == null || professionExcludedItems.contains(item.type) || item.type == Material.EMERALD || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) + emeraldsValue >= itemPrice) {
break // Достаточно средств, включая изумруды
}
}
return barterItems
}
User
Я понял, что надо сделать. В for (item in inventory) надо просто добавить сортировку инвентаря по типу предмета, сделав так, чтобы первыми всегда были EMERALD.
Assistant
Чтобы отсортировать инвентарь так, чтобы изумруды (EMERALD) были первыми, вы можете использовать метод сортировки перед тем, как проходить по элементам инвентаря. Так, в первую очередь вы будете обрабатывать изумруды, а затем остальные предметы.
Вот как можно сделать это:
kotlin
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
// Получаем список всех предметов в инвентаре и сортируем их так, чтобы EMERALD были первыми
val sortedInventory = inventory.filterNotNull().sortedBy { if (it.type == Material.EMERALD) 0 else 1 }
// Проходим по отсортированному инвентарю и собираем необходимую стоимость
for (item in sortedInventory) {
if (professionExcludedItems.contains(item.type) || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
// Проверяем, достаточно ли собранных элементов, включая стоимость
if (calculateItemListPrice(barterItems) >= itemPrice) {
break // Достаточно предметов для завершения обмена
}
}
return barterItems
}
Объяснение изменений:
Сортировка инвентаря: Мы используем sortedBy, чтобы отсортировать элементы по типу. Предметы с типом Material.EMERALD получают приоритет, так как они имеют значение 0, в то время как все остальные получат значение 1.
Фильтрация не-null: Используем filterNotNull(), чтобы исключить любые null элементы из инвентаря перед сортировкой.
Проход по отсортированному инвентарю: Теперь мы проходим по отсортированному инвентарю и добавляем предметы в barterItems, пока не достигнем необходимой цены.
Таким образом, изумруды будут обрабатываться в первую очередь, и при наличии их в инвентаре вы сможете максимально эффективно использовать их стоимость для завершения транзакции.
User
Что значит 0 else 1? Это индексы?
Assistant
В выражении sortedBy { if (it.type == Material.EMERALD) 0 else 1 } используются не индексы, а значения, чтобы определить порядок сортировки. Давайте разберем, как это работает:
sortedBy: Этот метод сортирует коллекцию по заданному критерию.
Сравнение по значению: В данном случае мы используем условное выражение if для присвоения значения:
Если предмет имеет тип Material.EMERALD, возвращается 0.
Если это не изумруд, возвращается 1.
Как это влияет на сортировку?
Метод sortedBy отсортирует элементы в порядке возрастания. Это значит, что элементы с меньшими значениями будут расположены первыми.
В вашем случае все изумруды получают значение 0, а все остальные предметы — значение 1.
Следовательно, все изумруды будут находиться в начале отсортированного списка, а остальные предметы будут следовать за ними.
Пример:
Предположим, что в инвентаре есть следующие предметы:
2 изумруда
1 меч
1 яблоко
После сортировки с использованием sortedBy вы получите такой порядок:
Изумруд 1 (EMERALD)
Изумруд 2 (EMERALD)
Меч (SWORD)
Яблоко (APPLE)
Так что, используя 0 для изумрудов и 1 для всех остальных, мы гарантируем, что изумруды всегда будут в начале списка при сортировке инвентаря.
User
Добавь документационные коментарии.
kotlin
Assistant
Добавление документационных комментариев (или Javadoc в случае Java) к коду улучшит его читаемость и понятность, а также поможет другим разработчикам (или вам в будущем) легче ориентироваться в функционале. Вот как может выглядеть ваш код с добавленными комментариями:
kotlin
User
Теперь мне нужно добавить метод, который бы округлял цены. Скажем, покупаемый предмет стоит 450,астоимостьодногоизумруда—500. Так как изумруд нельзя разделить, нужно придумать решение проблемы для таких ситуаций.
Assistant
Чтобы решить проблему округления цен и избежать ситуации, когда вы не можете использовать изумруды (или другие предметы с целыми значениями), можно использовать несколько подходов. Один из простых способов — это округлить цены предметов до ближайшего целого значения, которое можно получить с использованием доступных предметов, или использовать более сложную стратегию, такую как округление вверх.
Вот как вы можете реализовать метод округления цен в вашем классе MerchantEnhancer. Я добавлю метод roundPrice, который будет округлять цены в зависимости от доступных предметов.
Пример реализации:
kotlin
/**
* Округляет цену до ближайшего значения, которое можно получить с использованием предметов.
* Если цена меньше стоимости одного предмета, возвращает стоимость одного предмета.
*
* @param price цена, которую нужно округлить.
* @param itemStack идентификатор предмета, стоимость которого используется для округления.
* @return округленная цена.
*/
private fun roundPrice(price: Int, itemStack: ItemStack): Int {
val itemValue = calculateItemPrice(itemStack)
if (itemValue <= 0) return price // Если стоимость предмета некорректна, возвращаем исходную цену
val roundedPrice = ((price + itemValue - 1) / itemValue) * itemValue // Округляем вверх
return roundedPrice
}
Как использовать метод roundPrice:
Если вы хотите интегрировать округление в метод prepareTransaction, вы можете сделать это следующим образом:
kotlin
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
var itemPrice = calculateItemPrice(itemToBuy)
itemPrice = roundPrice(itemPrice, ItemStack(Material.EMERALD, 1)) // Округляем цену с использованием изумрудов
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
if (itemPrice > inventoryPrice) return Transaction(true, emptyList(), itemPrice, inventoryPrice)
val barterItems = this.gatherBarterItems(inventory, merchant.profession, itemPrice)
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
class MerchantEnhancer(plugin: QuestIntelligence) {
private val pricing: YamlConfiguration = YamlConfiguration.loadConfiguration(File(plugin.dataFolder, "pricing.yml"))
private val items: MutableList<MutableMap<*, *>> = pricing.getMapList("items")
val professionItems: MutableMap<Profession, List<ItemStack>> = mutableMapOf()
init {
initializeProfessionItems(plugin)
}
private fun initializeProfessionItems(plugin: QuestIntelligence) {
val professions = Registry.VILLAGER_PROFESSION.toList()
for (profession in professions) {
if (!plugin.config.contains("profession.$profession")) {
plugin.logger.warning("Профессия $profession отсутствует в конфигурации!")
continue
}
val lines = plugin.config.getStringList("profession.$profession.item-priority")
val itemList: MutableList<ItemStack> = lines.mapNotNull { parseItemLine(it) }.toMutableList()
professionItems[profession] = itemList
plugin.logger.info(profession.toString())
}
}
private fun parseItemLine(line: String): ItemStack? {
val (materialName, amountStr) = line.split("~").let { it[0] to it[1] }
val amount = amountStr.toIntOrNull() ?: return null
return ItemStack(Material.valueOf(materialName), amount)
}
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
val itemPrice = calculateItemPrice(itemToBuy)
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
if (itemPrice > inventoryPrice) {
return Transaction(true, emptyList(), itemPrice, inventoryPrice)
}
val barterItems = gatherBarterItems(inventory, merchant.profession, itemPrice)
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
for (item in inventory) {
if (item == null || professionExcludedItems.contains(item.type) || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) >= itemPrice) {
break
}
}
return barterItems
}
data class Transaction(val isCancelled: Boolean, val barterItems: List<ItemStack>, val itemPrice: Int, val villagerInventoryPrice: Int)
private fun calculateItemListPrice(itemList: List<ItemStack>): Int {
return itemList.sumOf { calculateItemPrice(it) }
}
private fun calculateInventoryPrice(inventory: Inventory): Int {
return inventory.sumOf { it?.let { calculateItemPrice(it) } ?: 0 }
}
private fun calculateItemPrice(item: ItemStack): Int {
return getMaterialPrice(item.type) * item.amount
}
private fun getMaterialPrice(material: Material): Int {
return items.find { it["name"] == material.name }
?.get("value") as? Int ?: 0
}
}
Основные изменения:
Выделение метода initializeProfessionItems: Логика инициализации профессий вынесена в отдельный метод для улучшения читаемости и уменьшения размера конструктора.
Выделение метода parseItemLine: Парсинг строки с предметом вынесен в отдельный метод, что делает код чище.
Метод gatherBarterItems: Логика сбора предметов для обмена вынесена в отдельный метод, что улучшает читаемость кода и изолирует логику.
Использование emptyList(): возвращение пустого списка вместо создания нового mutableListOf() в случае неудачи.
Эти изменения помогут сохранить функциональность вашего кода, улучшив при этом его читаемость и поддерживаемость.
class MerchantEnhancer(plugin: QuestIntelligence) {
private val pricing: YamlConfiguration = YamlConfiguration.loadConfiguration(File(plugin.dataFolder, "pricing.yml"))
private val items: MutableList<MutableMap<*, *>> = pricing.getMapList("items")
val professionItems: MutableMap<Profession, List<ItemStack>> = mutableMapOf()
init {
initializeProfessionItems(plugin)
}
private fun initializeProfessionItems(plugin: QuestIntelligence) {
val professions = Registry.VILLAGER_PROFESSION.toList()
for (profession in professions) {
if (!plugin.config.contains("profession.$profession")) {
plugin.logger.warning("Профессия $profession отсутствует в конфигурации!")
continue
}
val lines = plugin.config.getStringList("profession.$profession.item-priority")
val itemList: MutableList<ItemStack> = lines.mapNotNull { parseItemLine(it) }.toMutableList()
professionItems[profession] = itemList
plugin.logger.info(profession.toString())
}
}
private fun parseItemLine(line: String): ItemStack? {
val (materialName, amountStr) = line.split("~").let { it[0] to it[1] }
val amount = amountStr.toIntOrNull() ?: return null
return ItemStack(Material.valueOf(materialName), amount)
}
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
val itemPrice = calculateItemPrice(itemToBuy)
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
if (itemPrice > inventoryPrice) {
return Transaction(true, emptyList(), itemPrice, inventoryPrice)
}
val barterItems = gatherBarterItems(inventory, merchant.profession, itemPrice)
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
for (item in inventory) {
if (item == null || professionExcludedItems.contains(item.type) || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) >= itemPrice) {
break // Достаточно предметов для завершения обмена
}
}
return barterItems
}
data class Transaction(val isCancelled: Boolean, val barterItems: List<ItemStack>, val itemPrice: Int, val villagerInventoryPrice: Int)
private fun calculateItemListPrice(itemList: List<ItemStack>): Int {
return itemList.sumOf { calculateItemPrice(it) }
}
private fun calculateInventoryPrice(inventory: Inventory): Int {
return inventory.sumOf { it?.let { calculateItemPrice(it) } ?: 0 }
}
private fun calculateItemPrice(item: ItemStack): Int {
return getMaterialPrice(item.type) * item.amount
}
private fun getMaterialPrice(material: Material): Int {
return items.find { it["name"] == material.name }
?.get("value") as? Int ?: 0 // Возвращает 0, если материал не найден
}
}
Обратите внимание:
Все методы и конструкции отформатированы так, чтобы были равномерные отступы, что улучшает читаемость кода.
Комментарии оставлены в тех местах, где это необходимо для понимания логики кода.
Код выглядит согласованно и легко воспринимается для прочтения или модификации в будущем.
Объяснение изменений:
Подсчет стоимости изумрудов: Сначала мы проходим инвентарь и добавляем цены всех изумрудов (если такие есть) в переменную emeraldsValue, а также добавляем сами изумруды в список barterItems.
Проверка суммы: После подсчета стоимости изумрудов мы проверяем, хватает ли их для выполнения транзакции.
Сбор остальных предметов: Если стоимости изумрудов недостаточно, переходим ко второму циклу, чтобы добавить другие предметы, пока не достигнем необходимой суммы, включая стоимость изумрудов.
Теперь логика будет таковой: если в инвентаре есть изумруды, они будут учитываться в первой очереди при подсчете необходимой суммы для выполнения транзакции.
class MerchantEnhancer(private val plugin: QuestIntelligence) {
private val pricingConfig: YamlConfiguration = YamlConfiguration.loadConfiguration(File(plugin.dataFolder, "pricing.yml"))
private val itemPriceMap: MutableList<MutableMap<*, *>> = pricingConfig.getMapList("items")
val professionItems: MutableMap<Profession, List<ItemStack>> = mutableMapOf()
init {
this.initializeProfessionItems()
}
private fun initializeProfessionItems() {
for (profession in Registry.VILLAGER_PROFESSION.toList()) {
if (!plugin.config.contains("profession.$profession")) {
plugin.logger.warning("Профессия $profession отсутствует в конфигурации!")
continue
}
val lines = plugin.config.getStringList("profession.$profession.item-priority")
val itemList: MutableList<ItemStack> = lines.mapNotNull { parseItemLine(it) }.toMutableList()
professionItems[profession] = itemList
plugin.logger.info(profession.toString())
}
}
private fun parseItemLine(line: String): ItemStack? {
val (materialName, amountStr) = line.split("~").let { it[0] to it[1] }
val amount = amountStr.toIntOrNull() ?: return null
return ItemStack(Material.valueOf(materialName), amount)
}
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
val itemPrice = calculateItemPrice(itemToBuy)
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
if (itemPrice > inventoryPrice) return Transaction(true, emptyList(), itemPrice, inventoryPrice)
val barterItems = this.gatherBarterItems(inventory, merchant.profession, itemPrice)
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
// Сортируем инвентарь так, чтобы первыми были изумруды
for (item in inventory.filterNotNull().sortedBy { if (it.type == Material.EMERALD) 0 else 1 }) {
if (professionExcludedItems.contains(item.type) || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) >= itemPrice) {
break
}
}
return barterItems
}
data class Transaction(val isCancelled: Boolean, val barterItems: List<ItemStack>, val itemPrice: Int, val villagerInventoryPrice: Int)
private fun calculateItemListPrice(itemList: List<ItemStack>): Int {
return itemList.sumOf { calculateItemPrice(it) }
}
private fun calculateInventoryPrice(inventory: Inventory): Int {
return inventory.sumOf { it?.let { calculateItemPrice(it) } ?: 0 }
}
private fun calculateItemPrice(item: ItemStack): Int {
return getMaterialPrice(item.type) * item.amount
}
private fun getMaterialPrice(material: Material): Int {
return itemPriceMap.find { it["name"] == material.name }
?.get("value") as? Int ?: 0
}
}
/**
* Класс MerchantEnhancer предназначен для управления процессом покупки у торговца в игре.
* Он инициализирует профессии, загружает цены предметов и обрабатывает транзакции.
*
* @param plugin экземпляр QuestIntelligence, необходимый для доступа к конфигурации и ресурсам.
*/
class MerchantEnhancer(private val plugin: QuestIntelligence) {
private val pricingConfig: YamlConfiguration = YamlConfiguration.loadConfiguration(File(plugin.dataFolder, "pricing.yml"))
private val itemPriceMap: MutableList<MutableMap<*, *>> = pricingConfig.getMapList("items")
val professionItems: MutableMap<Profession, List<ItemStack>> = mutableMapOf()
init {
this.initializeProfessionItems()
}
/**
* Инициализация профессий для торговцев.
* Загружает список предметов, которые могут использовать для торговли каждый тип профессии.
*/
private fun initializeProfessionItems() {
for (profession in Registry.VILLAGER_PROFESSION.toList()) {
if (!plugin.config.contains("profession.$profession")) {
plugin.logger.warning("Профессия $profession отсутствует в конфигурации!")
continue
}
val lines = plugin.config.getStringList("profession.$profession.item-priority")
val itemList: MutableList<ItemStack> = lines.mapNotNull { parseItemLine(it) }.toMutableList()
professionItems[profession] = itemList
plugin.logger.info(profession.toString())
}
}
/**
* Парсит строку с информацией о предмете, разделенной символом ~.
*
* @param line строка, представляющая предмет.
* @return объект ItemStack, если парсинг успешен; null в противном случае.
*/
private fun parseItemLine(line: String): ItemStack? {
val (materialName, amountStr) = line.split("~").let { it[0] to it[1] }
val amount = amountStr.toIntOrNull() ?: return null
return ItemStack(Material.valueOf(materialName), amount)
}
/**
* Подготавливает транзакцию покупки у торговца, вычисляя необходимую цену и собирая предметы для обмена.
*
* @param itemToBuy предмет, который игрок хочет купить.
* @param merchant торговец, с которым осуществляется обмен.
* @return объект Transaction, представляющий результат транзакции.
*/
fun prepareTransaction(itemToBuy: ItemStack, merchant: Villager): Transaction {
val itemPrice = calculateItemPrice(itemToBuy)
val inventory = merchant.quillInventory
val inventoryPrice = calculateInventoryPrice(inventory)
if (itemPrice > inventoryPrice) return Transaction(true, emptyList(), itemPrice, inventoryPrice)
val barterItems = this.gatherBarterItems(inventory, merchant.profession, itemPrice)
return Transaction(false, ImmutableList.copyOf(barterItems), itemPrice, inventoryPrice)
}
/**
* Сбор предметов для обмена из инвентаря торговца, учитывая профессию и требуемую цену.
*
* @param inventory инвентарь торговца.
* @param profession профессия торговца.
* @param itemPrice цена предмета, который игрок хочет купить.
* @return список предметов для обмена.
*/
private fun gatherBarterItems(inventory: Inventory, profession: Profession, itemPrice: Int): MutableList<ItemStack> {
val barterItems: MutableList<ItemStack> = mutableListOf()
val professionExcludedItems = professionItems[profession].orEmpty().map { it.type }
// Сортируем инвентарь так, чтобы первыми были изумруды
for (item in inventory.filterNotNull().sortedBy { if (it.type == Material.EMERALD) 0 else 1 }) {
if (professionExcludedItems.contains(item.type) || calculateItemPrice(item) <= 0) continue
barterItems.add(item)
if (calculateItemListPrice(barterItems) >= itemPrice) {
break
}
}
return barterItems
}
/**
* Данные класса, представляющие результат транзакции.
*
* @param isCancelled флаг, определяющий, была ли транзакция отменена.
* @param barterItems список предметов, собранных для обмена.
* @param itemPrice цена предмета, который игрок хочет купить.
* @param villagerInventoryPrice общая цена инвентаря торговца.
*/
data class Transaction(val isCancelled: Boolean, val barterItems: List<ItemStack>, val itemPrice: Int, val villagerInventoryPrice: Int)
/**
* Вычисляет общую цену списка предметов.
*
* @param itemList список предметов.
* @return общая цена.
*/
private fun calculateItemListPrice(itemList: List<ItemStack>): Int {
return itemList.sumOf { calculateItemPrice(it) }
}
/**
* Вычисляет общую цену инвентаря.
*
* @param inventory инвентарь.
* @return общая цена.
*/
private fun calculateInventoryPrice(inventory: Inventory): Int {
return inventory.sumOf { it?.let { calculateItemPrice(it) } ?: 0 }
}
/**
* Вычисляет цену отдельного предмета.
*
* @param item предмет, для которого вычисляется цена.
* @return цена предмета.
*/
private fun calculateItemPrice(item: ItemStack): Int {
return getMaterialPrice(item.type) * item.amount
}
/**
* Получает цену материала по его типу.
*
* @param material тип материала.
* @return цена материала или 0, если материал не найден.
*/
private fun getMaterialPrice(material: Material): Int {
return itemPriceMap.find { it["name"] == material.name }
?.get("value") as? Int ?: 0
}
}
Что было добавлено:
Общие комментарии к классу: Описание, что делает класс и его параметры.
Документация к методам: Описание каждого метода, его параметров и возвращаемого значения.
Документация к data классу Transaction: Описание всех полей класса.
Эти комментарии помогут другим разработчикам (или вам в будущем) быстро понять логику кода, его структуру и предназначение каждого метода.
Объяснение:
Метод roundPrice:
itemValue — цена предмета, который используется для округления (в данном случае изумруд, если он указан).
Округление производится с использованием целочисленного деления, чтобы получить ближайшую верхнюю целую цену, кратную стоимости выбранного предмета.
Если цена меньше стоимости одного предмета, метод возвращает оригинальную цену.
Интеграция в метод prepareTransaction:
Перед выполнением расчетов по инвентарю цена itemPrice округляется, чтобы гарантировать, что вы сможете использовать необходимые предметы для завершения транзакции.
Таким образом, вы сможете избежать ситуации, когда цена не может быть достигнута из-за дробных значений, а также обеспечить более эффективное использование предметов в транзакциях.