Skip to content

Commit

Permalink
Random fixes (#1120)
Browse files Browse the repository at this point in the history
* Refactor bazaar and roman numerals

* Revert name from api

* Fix neu id

* Fix roman numerals

* Apply suggestions from code review

* Fix level type

* Fix import

---------

Co-authored-by: Rime <[email protected]>
  • Loading branch information
kevinthegreat1 and Emirlol authored Jan 9, 2025
1 parent eb962b9 commit f239c9e
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 74 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import de.hysky.skyblocker.skyblock.item.tooltip.info.DataTooltipInfoType;
import de.hysky.skyblocker.skyblock.item.tooltip.info.TooltipInfoType;
import de.hysky.skyblocker.skyblock.itemlist.ItemRepository;
import de.hysky.skyblocker.skyblock.searchoverlay.SearchOverManager;
import de.hysky.skyblocker.utils.Constants;
import de.hysky.skyblocker.utils.scheduler.MessageScheduler;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
Expand All @@ -16,6 +15,7 @@
import net.minecraft.screen.slot.Slot;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import org.apache.commons.text.WordUtils;
import org.jetbrains.annotations.NotNull;
import org.lwjgl.glfw.GLFW;

Expand Down Expand Up @@ -64,7 +64,7 @@ public static void itemPriceLookup(ClientPlayerEntity player, @NotNull Slot slot

// Handle Enchanted Books
if (itemName.equals("Enchanted Book")) {
itemName = SearchOverManager.capitalizeFully(skyblockApiId.replace("ENCHANTMENT_", "").replaceAll("_\\d+", ""));
itemName = WordUtils.capitalizeFully(skyblockApiId.replace("ENCHANTMENT_", "").replaceAll("_\\d+", ""));
}

// Search up the item in the bazaar or auction house
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import de.hysky.skyblocker.skyblock.profileviewer.ProfileViewerPage;
import de.hysky.skyblocker.skyblock.profileviewer.ProfileViewerScreen;
import de.hysky.skyblocker.skyblock.tabhud.util.Ico;
import de.hysky.skyblocker.utils.RomanNumerals;
import it.unimi.dsi.fastutil.ints.IntList;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.font.TextRenderer;
Expand Down Expand Up @@ -43,7 +44,6 @@ public class GenericCategory implements ProfileViewerPage {
private final Map<String, IntList> tierRequirementsMap;
private final Map<String, String> ICON_TRANSLATION = Map.ofEntries(
Map.entry("MUSHROOM_COLLECTION", "RED_MUSHROOM"));
private final String[] ROMAN_NUMERALS = {"-", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX"};

public GenericCategory(JsonObject hProfile, JsonObject pProfile, String collection) {
collectionsMap = ProfileViewerScreen.getCollections();
Expand All @@ -63,7 +63,7 @@ private void setupItemStacks(JsonObject hProfile, JsonObject pProfile) {
ItemStack itemStack = ItemRepository.getItemStack(ICON_TRANSLATION.getOrDefault(collection, collection).replace(':', '-'));
itemStack = itemStack == null ? Ico.BARRIER.copy() : itemStack.copy();

if (itemStack.getItem().getName().getString().equals("Barrier")) {
if (itemStack.getItem().getName().getString().equals("Barrier")) {
itemStack.set(DataComponentTypes.CUSTOM_NAME, Text.of(collection));
System.out.println(collection);
System.out.println(this.category);
Expand Down Expand Up @@ -91,7 +91,7 @@ private void setupItemStacks(JsonObject hProfile, JsonObject pProfile) {

if (hProfile.get("members").getAsJsonObject().keySet().size() > 1) {
lore.add(Text.literal("Personal: " + COMMA_FORMATTER.format(personalColl)).setStyle(style).formatted(Formatting.GOLD));
lore.add(Text.literal("Co-op: " + COMMA_FORMATTER.format(totalCollection-personalColl)).setStyle(style).formatted(Formatting.AQUA));
lore.add(Text.literal("Co-op: " + COMMA_FORMATTER.format(totalCollection - personalColl)).setStyle(style).formatted(Formatting.AQUA));
}
lore.add(Text.literal("Collection: " + COMMA_FORMATTER.format(totalCollection)).setStyle(style).formatted(Formatting.YELLOW));

Expand Down Expand Up @@ -133,7 +133,7 @@ public void render(DrawContext context, int mouseX, int mouseY, float delta, int
Color colour = itemStack.hasGlint() ? Color.MAGENTA : Color.darkGray;
//DO NOT CHANGE THIS METHOD CALL! Aaron's Mod mixes in here to provide chroma text for max collections
//and changing the method called here will break that! Consult Aaron before making any changes :)
context.drawText(textRenderer, Text.literal(toRomanNumerals(cTier)), x + 9 - (textRenderer.getWidth(toRomanNumerals(cTier)) / 2), y + 21, colour.getRGB(), false);
context.drawText(textRenderer, Text.literal(RomanNumerals.decimalToRoman(cTier)), x + 9 - (textRenderer.getWidth(RomanNumerals.decimalToRoman(cTier)) / 2), y + 21, colour.getRGB(), false);
}
break;
}
Expand All @@ -145,8 +145,4 @@ public void render(DrawContext context, int mouseX, int mouseY, float delta, int
}
}
}

private String toRomanNumerals(int number) {
return number <= ROMAN_NUMERALS.length ? ROMAN_NUMERALS[number] : "Err";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import de.hysky.skyblocker.skyblock.item.tooltip.info.TooltipInfoType;
import de.hysky.skyblocker.utils.BazaarProduct;
import de.hysky.skyblocker.utils.NEURepoManager;
import de.hysky.skyblocker.utils.RomanNumerals;
import de.hysky.skyblocker.utils.scheduler.MessageScheduler;
import io.github.moulberry.repo.data.NEUItem;
import io.github.moulberry.repo.util.NEUId;
Expand All @@ -30,7 +31,6 @@
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal;

Expand All @@ -39,15 +39,8 @@ public class SearchOverManager {
private static final MinecraftClient CLIENT = MinecraftClient.getInstance();
private static final Logger LOGGER = LoggerFactory.getLogger("Skyblocker Search Overlay");

private static final Pattern BAZAAR_ENCHANTMENT_PATTERN = Pattern.compile("ENCHANTMENT_(\\D*)_(\\d+)");
private static final Pattern BAZAAR_ENCHANTMENT_PATTERN = Pattern.compile("Enchantment (\\D*) (\\d+)");
private static final String PET_NAME_START = "[Lvl {LVL}] ";
/**
* converts index (in array) +1 to a roman numeral
*/
private static final String[] ROMAN_NUMERALS = new String[]{
"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI",
"XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX"
};

private static @Nullable SignBlockEntity sign = null;
private static boolean signFront = true;
Expand All @@ -63,7 +56,7 @@ public class SearchOverManager {
private static HashSet<String> auctionItems = new HashSet<>();
private static HashSet<String> auctionPets = new HashSet<>();
private static HashSet<String> starableItems = new HashSet<>();
private static HashMap<String, String> namesToId = new HashMap<>();
private static HashMap<String, String> namesToNeuId = new HashMap<>();

public static String[] suggestionsArray = {};

Expand Down Expand Up @@ -97,7 +90,7 @@ private static void loadItems() {
HashSet<String> auctionItems = new HashSet<>();
HashSet<String> auctionPets = new HashSet<>();
HashSet<String> starableItems = new HashSet<>();
HashMap<String, String> namesToId = new HashMap<>();
HashMap<String, String> namesToNeuId = new HashMap<>();

//get bazaar items
try {
Expand All @@ -106,36 +99,32 @@ private static void loadItems() {
Object2ObjectMap<String, BazaarProduct> products = TooltipInfoType.BAZAAR.getData();
for (Map.Entry<String, BazaarProduct> entry : products.entrySet()) {
BazaarProduct product = entry.getValue();
String id = product.id();
int sellVolume = product.sellVolume();
if (sellVolume == 0)
continue; //do not add items that do not sell e.g. they are not actual in the bazaar
Matcher matcher = BAZAAR_ENCHANTMENT_PATTERN.matcher(id);
if (matcher.matches()) {//format enchantments
//remove ultimate if in name
String name = matcher.group(1);
if (!name.contains("WISE")) { //only way found to remove ultimate from everything but ultimate wise
name = name.replace("ULTIMATE_", "");
}
name = name.replace("_", " ");
name = capitalizeFully(name);
int enchantLevel = Integer.parseInt(matcher.group(2));
String level = "";
if (enchantLevel > 0) {
level = ROMAN_NUMERALS[enchantLevel - 1];
}
bazaarItems.add(name + " " + level);
namesToId.put(name + " " + level, matcher.group(1) + ";" + matcher.group(2));
continue;
}
//look up id for name
NEUItem neuItem = NEURepoManager.NEU_REPO.getItems().getItemBySkyblockId(id);
if (neuItem != null) {
String name = Formatting.strip(neuItem.getDisplayName());
bazaarItems.add(name);
namesToId.put(name, id);
continue;
}
String id = product.id();
String name = product.name();
int sellVolume = product.sellVolume();
if (sellVolume == 0)
continue; //do not add items that do not sell e.g. they are not actual in the bazaar
Matcher matcher = BAZAAR_ENCHANTMENT_PATTERN.matcher(name);
if (matcher.matches()) {//format enchantments
name = matcher.group(1);
if (!name.contains("Ultimate Wise")) {
name = name.replace("Ultimate ", "");
}

String level = matcher.group(2);
name += " " + RomanNumerals.decimalToRoman(Integer.parseInt(level));
bazaarItems.add(name);
namesToNeuId.put(name, id.substring(0, id.lastIndexOf('_')).replace("ENCHANTMENT_", "") + ";" + level);
continue;
}
//look up id for name
NEUItem neuItem = NEURepoManager.NEU_REPO.getItems().getItemBySkyblockId(id);
if (neuItem != null) {
name = Formatting.strip(neuItem.getDisplayName());
bazaarItems.add(name);
namesToNeuId.put(name, id);
continue;
}
}
} catch (Exception e) {
LOGGER.error("[Skyblocker] Failed to load bazaar item list! ", e);
Expand Down Expand Up @@ -164,7 +153,7 @@ private static void loadItems() {
starableItems.add(name.toLowerCase());
}
auctionItems.add(name);
namesToId.put(name, id);
namesToNeuId.put(name, id);
}
}
} catch (Exception e) {
Expand All @@ -175,22 +164,7 @@ private static void loadItems() {
SearchOverManager.auctionItems = auctionItems;
SearchOverManager.auctionPets = auctionPets;
SearchOverManager.starableItems = starableItems;
SearchOverManager.namesToId = namesToId;
}

/**
* Capitalizes the first letter off every word in a string
*
* @param str string to capitalize
*/
public static String capitalizeFully(String str) {
if (str == null || str.isEmpty()) {
return str;
}

return Arrays.stream(str.split("\\s+"))
.map(t -> t.substring(0, 1).toUpperCase() + t.substring(1).toLowerCase())
.collect(Collectors.joining(" "));
SearchOverManager.namesToNeuId = namesToNeuId;
}

/**
Expand Down Expand Up @@ -265,7 +239,7 @@ protected static String getSuggestion(int index) {
}

protected static String getSuggestionId(int index) {
return namesToId.get(getSuggestion(index));
return namesToNeuId.get(getSuggestion(index));
}

/**
Expand All @@ -287,7 +261,7 @@ protected static String getHistory(int index) {
}

protected static String getHistoryId(int index) {
return namesToId.get(getHistory(index));
return namesToNeuId.get(getHistory(index));
}

/**
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/de/hysky/skyblocker/utils/BazaarProduct.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@

import it.unimi.dsi.fastutil.objects.Object2ObjectMap;

public record BazaarProduct(String id, OptionalDouble buyPrice, OptionalDouble sellPrice, int buyVolume, int sellVolume) {
public record BazaarProduct(String id, String name, OptionalDouble buyPrice, OptionalDouble sellPrice, int buyVolume, int sellVolume) {
private static final Codec<BazaarProduct> CODEC = RecordCodecBuilder.create(instance -> instance.group(
Codec.STRING.fieldOf("id").forGetter(BazaarProduct::id),
Codec.STRING.fieldOf("name").forGetter(BazaarProduct::name),
CodecUtils.optionalDouble(Codec.DOUBLE.lenientOptionalFieldOf("buyPrice")).forGetter(BazaarProduct::buyPrice),
CodecUtils.optionalDouble(Codec.DOUBLE.lenientOptionalFieldOf("sellPrice")).forGetter(BazaarProduct::sellPrice),
Codec.INT.fieldOf("buyVolume").forGetter(BazaarProduct::buyVolume),
Expand Down
34 changes: 33 additions & 1 deletion src/main/java/de/hysky/skyblocker/utils/RomanNumerals.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
package de.hysky.skyblocker.utils;

import it.unimi.dsi.fastutil.ints.Int2ObjectLinkedOpenHashMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
import org.jetbrains.annotations.NotNull;

public class RomanNumerals {
private RomanNumerals() {}
private static final Int2ObjectMap<String> ROMAN_NUMERALS = Int2ObjectMaps.unmodifiable(new Int2ObjectLinkedOpenHashMap<>(
new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1},
new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}
));

private RomanNumerals() {}

private static int getDecimalValue(char romanChar) {
return switch (romanChar) {
Expand All @@ -19,6 +29,7 @@ private static int getDecimalValue(char romanChar) {
/**
* Checks if a string is a valid roman numeral.
* It's the caller's responsibility to clean up the string before calling this method (such as trimming it).
*
* @param romanNumeral The roman numeral to check.
* @return True if the string is a valid roman numeral, false otherwise.
* @implNote This will only check if the string contains valid roman numeral characters. It won't check if the numeral is well-formed.
Expand Down Expand Up @@ -51,4 +62,25 @@ public static int romanToDecimal(String romanNumeral) {
}
return decimal;
}

/**
* Converts a decimal number to a roman numeral.
*
* @param decimal The decimal number to convert.
* @return The roman numeral, or an empty string if the number is out of range.
*/
@NotNull
public static String decimalToRoman(int decimal) {
if (decimal <= 0 || decimal >= 4000) return "";
StringBuilder roman = new StringBuilder();
for (Int2ObjectMap.Entry<String> entry : ROMAN_NUMERALS.int2ObjectEntrySet()) {
int value = entry.getIntKey();
String numeral = entry.getValue();
while (decimal >= value) {
roman.append(numeral);
decimal -= value;
}
}
return roman.toString();
}
}
18 changes: 16 additions & 2 deletions src/test/java/de/hysky/skyblocker/utils/RomanNumeralsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@

class RomanNumeralsTest {
@Test
void testToRoman() {
void testRomanToDecimal() {
// Test the first 50 numbers
String[] expected = new String[]{"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX", "XXXI", "XXXII", "XXXIII", "XXXIV", "XXXV", "XXXVI", "XXXVII", "XXXVIII", "XXXIX", "XL", "XLI", "XLII", "XLIII", "XLIV", "XLV", "XLVI", "XLVII", "XLVIII", "XLIX", "L"};
for (int i = 1; i <= 50; i++) {
Assertions.assertEquals(i, RomanNumerals.romanToDecimal(expected[i-1]));
Assertions.assertEquals(i, RomanNumerals.romanToDecimal(expected[i - 1]));
}
Assertions.assertEquals(100, RomanNumerals.romanToDecimal("C"));
Assertions.assertEquals(400, RomanNumerals.romanToDecimal("CD"));
Expand All @@ -32,4 +32,18 @@ void isValidRoman() {
Assertions.assertFalse(RomanNumerals.isValidRomanNumeral(null));
Assertions.assertFalse(RomanNumerals.isValidRomanNumeral(""));
}

@Test
void testDecimalToRoman() {
String[] expected = new String[]{"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX", "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX", "XXXI", "XXXII", "XXXIII", "XXXIV", "XXXV", "XXXVI", "XXXVII", "XXXVIII", "XXXIX", "XL", "XLI", "XLII", "XLIII", "XLIV", "XLV", "XLVI", "XLVII", "XLVIII", "XLIX", "L"};
for (int i = 1; i <= 50; i++) {
Assertions.assertEquals(expected[i - 1], RomanNumerals.decimalToRoman(i));
}
Assertions.assertEquals("C", RomanNumerals.decimalToRoman(100));
Assertions.assertEquals("CD", RomanNumerals.decimalToRoman(400));
Assertions.assertEquals("D", RomanNumerals.decimalToRoman(500));
Assertions.assertEquals("CM", RomanNumerals.decimalToRoman(900));
Assertions.assertEquals("M", RomanNumerals.decimalToRoman(1000));
Assertions.assertEquals("MCMXCIX", RomanNumerals.decimalToRoman(1999));
}
}

0 comments on commit f239c9e

Please sign in to comment.