Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 50 additions & 45 deletions src/main/java/world/bentobox/challenges/tasks/TryToComplete.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -13,11 +13,11 @@
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.UUID;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
Expand DownExpand Up@@ -1065,26 +1065,12 @@ Map<ItemStack, Integer> removeItems(List<ItemStack> requiredItemList, int factor
for (ItemStack required : requiredItemList)
{
int amountToBeRemoved = required.getAmount() * factor;
List<ItemStack> itemsInInventory;

if (this.user.getInventory() == null)
{
// Sanity check. User always has inventory at this point of code.
itemsInInventory = Collections.emptyList();
}
else if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
// Use collecting method that ignores item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.getType().equals(required.getType()))
.collect(Collectors.toList());
}
else
{
// Use collecting method that compares item meta.
itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).filter(i -> i.isSimilar(required)).collect(Collectors.toList());
}
// Use helper method that handles ignore-metadata logic including potion types.
List<ItemStack> itemsInInventory = Arrays.stream(user.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

for (ItemStack itemStack : itemsInInventory)
{
Expand DownExpand Up@@ -1876,6 +1862,45 @@ private boolean hasRequiredTeamPresence()
}


/**
* Checks if two items match, considering the ignore-metadata setting. For potion-like materials
* that are in the ignore-metadata set, compares the base potion type while ignoring other metadata.
* For non-potion materials in the ignore-metadata set, uses type-only comparison. For materials
* not in the ignore-metadata set, uses full similarity comparison.
*
* @param candidate candidate item from inventory
* @param required required item template
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if the items match
*/
private static boolean itemsMatch(ItemStack candidate, ItemStack required, Set<Material> ignoreMetaData)
{
if (candidate == null || required == null)
{
return false;
}

if (!candidate.getType().equals(required.getType()))
{
return false;
}

// If metadata should not be ignored, use full similarity check
if (!ignoreMetaData.contains(required.getType()))
{
return candidate.isSimilar(required);
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (Utils.isPotionLike(required.getType()))
{
return Utils.comparePotionType(candidate, required);
}

// For non-potion materials, type-only matching is sufficient
return true;
}

/**
* Counts how many of {@code required} a single player holds, honouring the challenge's
* ignore-meta-data setting.
Expand All@@ -1886,17 +1911,9 @@ private boolean hasRequiredTeamPresence()
*/
private int countInInventory(Player player, ItemStack required)
{
if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
mapToInt(ItemStack::getAmount).sum();
}

return Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
mapToInt(ItemStack::getAmount).sum();
}

Expand All@@ -1916,22 +1933,10 @@ private int removeFromInventory(Player player, ItemStack required, int amount)
return 0;
}

List<ItemStack> itemsInInventory;

if (this.getInventoryRequirements().getIgnoreMetaData().contains(required.getType()))
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.getType().equals(required.getType())).
toList();
}
else
{
itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> i.isSimilar(required)).
toList();
}
List<ItemStack> itemsInInventory = Arrays.stream(player.getInventory().getContents()).
filter(Objects::nonNull).
filter(i -> itemsMatch(i, required, this.getInventoryRequirements().getIgnoreMetaData())).
toList();

int toRemove = amount;

Expand Down
84 changes: 83 additions & 1 deletion src/main/java/world/bentobox/challenges/utils/Utils.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -59,6 +59,52 @@ else if (stack == input)
}


/**
* Checks if a material is potion-like (potions, splash potions, lingering potions, tipped arrows).
*
* @param material the material to check
* @return true if the material is potion-like
*/
public static boolean isPotionLike(Material material)
{
return material == Material.POTION ||
material == Material.SPLASH_POTION ||
material == Material.LINGERING_POTION ||
material == Material.TIPPED_ARROW;
}

/**
* Compares the base potion type of two potion items. Returns true if they have the same
* base potion type, ignoring custom effects, lore, and other metadata.
*
* @param first first potion item
* @param second second potion item
* @return true if both items have the same base potion type
*/
public static boolean comparePotionType(@Nullable ItemStack first, @Nullable ItemStack second)
{
if (first == null || second == null)
{
return false;
}

PotionType firstType = null;
PotionType secondType = null;

if (first.hasItemMeta() && first.getItemMeta() instanceof PotionMeta potionMeta)
{
firstType = potionMeta.getBasePotionType();
}

if (second.hasItemMeta() && second.getItemMeta() instanceof PotionMeta potionMeta)
{
secondType = potionMeta.getBasePotionType();
}

// If either has no potion meta, they're only equal if both are missing the meta
return java.util.Objects.equals(firstType, secondType);
}

/**
* This method groups input items in single itemstack with correct amount and returns it.
* Allows to remove duplicate items from list.
Expand All@@ -84,7 +130,7 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set

// Merge items which meta can be ignored or is similar to item in required list.
if (Utils.isSimilarNoDurability(required, item) ||
ignoreMetaData.contains(item.getType()) && item.getType().equals(required.getType()))
itemsMatchIgnoreMetadata(required, item, ignoreMetaData))
{
required.setAmount(required.getAmount() + item.getAmount());
isUnique = false;
Expand All@@ -103,6 +149,42 @@ public static List<ItemStack> groupEqualItems(List<ItemStack> requiredItems, Set
return returnItems;
}

/**
* Checks if two items match when metadata should be ignored. For potion-like materials,
* compares the base potion type. For non-potion materials, uses type-only comparison.
*
* @param first first item
* @param second second item
* @param ignoreMetaData set of materials to ignore metadata for
* @return true if items match according to the ignore-metadata rules
*/
private static boolean itemsMatchIgnoreMetadata(@Nullable ItemStack first, @Nullable ItemStack second, Set<Material> ignoreMetaData)
{
if (first == null || second == null)
{
return false;
}

if (!first.getType().equals(second.getType()))
{
return false;
}

if (!ignoreMetaData.contains(first.getType()))
{
return false;
}

// Metadata is being ignored. For potion-like materials, still compare base potion type.
if (isPotionLike(first.getType()))
{
return comparePotionType(first, second);
}

// For non-potion materials, type-only matching is sufficient
return true;
}


/**
* This method transforms given World into GameMode name. If world is not a GameMode
Expand Down
114 changes: 114 additions & 0 deletions src/test/java/world/bentobox/challenges/tasks/TryToCompleteTest.java
Original file line numberDiff line numberDiff line change
Expand Up@@ -35,6 +35,8 @@
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.potion.PotionType;
import org.bukkit.util.BoundingBox;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.jupiter.api.AfterEach;
Expand All@@ -57,6 +59,7 @@
import world.bentobox.challenges.database.object.requirements.StatisticRequirements.StatisticRec;
import world.bentobox.challenges.managers.ChallengesManager;
import world.bentobox.challenges.tasks.TryToComplete.ChallengeResult;
import world.bentobox.challenges.utils.Utils;
import world.bentobox.level.Level;

/**
Expand DownExpand Up@@ -852,6 +855,117 @@ void testFreeChallengeNoLevelCheck() {
verify(cm, never()).getLevel(any(Challenge.class));
}

// -------------------------------------------------------------------------
// Tests for issue #320: Potion type comparison when metadata is ignored
// -------------------------------------------------------------------------

@Test
void testPotionComparisonIgnoreMetadataSameType() {
// Test that potions with same base type match when metadata is ignored
// by using Utils.groupEqualItems which should group them together
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion1.setAmount(1);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion2.setAmount(1);
// Add different custom name to swiftnessPotion2 to ensure metadata differs
PotionMeta meta = (PotionMeta) swiftnessPotion2.getItemMeta();
if (meta != null) {
meta.setDisplayName("Fancy Swiftness");
swiftnessPotion2.setItemMeta(meta);
}

// When grouping items with ignore-metadata set for potions,
// potions with the same base type should be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion1, swiftnessPotion2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both swiftness potions should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Potions with same base type should be grouped together");
assertEquals(2, grouped.get(0).getAmount(), "Grouped potion should have combined amount");
assertEquals(Material.POTION, grouped.get(0).getType(), "Grouped potion should be POTION");
}

@Test
void testPotionComparisonIgnoreMetadataDifferentType() {
// Test that potions with different base types DON'T group when metadata is ignored
ItemStack swiftnessPotion = createPotion(Material.POTION, PotionType.SWIFTNESS);
swiftnessPotion.setAmount(1);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);
strengthPotion.setAmount(1);

// When grouping potions with different base types and ignore-metadata set,
// they should NOT be grouped together
Set<Material> ignoreMetaData = Set.of(Material.POTION);
List<ItemStack> requiredItems = Arrays.asList(swiftnessPotion, strengthPotion);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Different potion types should NOT be grouped
assertEquals(2, grouped.size(), "Potions with different base types should NOT be grouped");
assertEquals(1, grouped.get(0).getAmount(), "First potion should keep original amount");
assertEquals(1, grouped.get(1).getAmount(), "Second potion should keep original amount");
}

@Test
void testPotionComparisonHelperMethod() {
// Unit test for the helper method that checks if items match with potion type comparison
ItemStack swiftnessPotion1 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack swiftnessPotion2 = createPotion(Material.POTION, PotionType.SWIFTNESS);
ItemStack strengthPotion = createPotion(Material.POTION, PotionType.STRENGTH);

// Test that same potion type matches
assertTrue(Utils.comparePotionType(swiftnessPotion1, swiftnessPotion2),
"Potions with same base type should compare as equal");

// Test that different potion types don't match
assertFalse(Utils.comparePotionType(swiftnessPotion1, strengthPotion),
"Potions with different base types should not compare as equal");

// Test that potion-like check works
assertTrue(Utils.isPotionLike(Material.POTION),
"POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.SPLASH_POTION),
"SPLASH_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.LINGERING_POTION),
"LINGERING_POTION should be recognized as potion-like");
assertTrue(Utils.isPotionLike(Material.TIPPED_ARROW),
"TIPPED_ARROW should be recognized as potion-like");
assertFalse(Utils.isPotionLike(Material.DIRT),
"DIRT should not be recognized as potion-like");
}

@Test
void testNonPotionIgnoreMetadataUnchanged() {
// Test that non-potion materials still use type-only comparison
ItemStack dirt1 = new ItemStack(Material.DIRT);
dirt1.setAmount(1);
ItemStack dirt2 = new ItemStack(Material.DIRT);
dirt2.setAmount(1);

// When grouping non-potion items with ignore-metadata set,
// they should be grouped together by type alone
Set<Material> ignoreMetaData = Set.of(Material.DIRT);
List<ItemStack> requiredItems = Arrays.asList(dirt1, dirt2);
List<ItemStack> grouped = Utils.groupEqualItems(requiredItems, ignoreMetaData);

// Both dirt items should be grouped into one stack with amount 2
assertEquals(1, grouped.size(), "Non-potion items with same type should be grouped");
assertEquals(2, grouped.get(0).getAmount(), "Grouped items should have combined amount");
}

/**
* Helper method to create a potion ItemStack with specified base potion type
*/
private ItemStack createPotion(Material material, PotionType potionType) {
ItemStack potion = new ItemStack(material);
PotionMeta meta = (PotionMeta) potion.getItemMeta();
if (meta != null) {
meta.setBasePotionType(potionType);
potion.setItemMeta(meta);
}
return potion;
}

// -------------------------------------------------------------------------
// Consumption/Removal tests (Issue #111)
// -------------------------------------------------------------------------
Expand Down
Loading