Repository navigation
Let players see the recipes of alloys they have forged #51
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
f9ad319
Let players see the recipes of alloys they have forged
XxFran10xX a02c60b
Record new alloys at forge time and move records on rename
XxFran10xX 6404f64
Record known alloy recipes by combo, not by alloy id
XxFran10xX 4a2a6ba
Keep unreadable recipe files, write atomically, retry failed saves
XxFran10xX ba7b43a
Cover the remaining branches for the 100% coverage gate
XxFran10xX 74acb6c
Lowercase alloy recipe keys with Locale.ROOT
XxFran10xX File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
159 changes: 159 additions & 0 deletions
159
src/main/java/net/tfminecraft/advancedcrafting/lifecycle/KnownAlloyRecipes.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| package net.tfminecraft.advancedcrafting.lifecycle; | ||
|
|
||
| import java.io.File; | ||
| import java.io.FileInputStream; | ||
| import java.io.IOException; | ||
| import java.io.InputStreamReader; | ||
| import java.nio.charset.StandardCharsets; | ||
| import java.nio.file.AtomicMoveNotSupportedException; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.nio.file.StandardCopyOption; | ||
| import java.util.ArrayList; | ||
| import java.util.HashMap; | ||
| import java.util.HashSet; | ||
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.Map; | ||
| import java.util.Set; | ||
| import java.util.UUID; | ||
|
|
||
| import org.json.simple.JSONArray; | ||
| import org.json.simple.parser.JSONParser; | ||
|
|
||
| import net.tfminecraft.advancedcrafting.AdvancedCrafting; | ||
| import net.tfminecraft.advancedcrafting.managers.AlloyManager; | ||
| import net.tfminecraft.advancedcrafting.objects.alloys.Alloy; | ||
| import net.tfminecraft.advancedcrafting.objects.data.AlloyRecipe; | ||
|
|
||
| /** | ||
| * The alloy recipes each account has forged, as combo keys ({@code base|catalyst,catalyst}). | ||
| * A combo never changes when its alloy is named or renamed and is never reused, unlike alloy ids. | ||
| * Files live in {@code data/known-alloy-recipes/<uuid>.json}. A player without a file yet starts | ||
| * from the alloys {@link PlayerAlloyForgeTracker} has on record for them. | ||
| */ | ||
| public final class KnownAlloyRecipes { | ||
| private static KnownAlloyRecipes instance; | ||
|
|
||
| private final File folder; | ||
| private final Map<UUID, Set<String>> cache = new HashMap<>(); | ||
| /** Accounts whose file could not be read; it is never overwritten this session. */ | ||
| private final Set<UUID> unreadable = new HashSet<>(); | ||
|
|
||
| public KnownAlloyRecipes(File dataFolder) { | ||
| this.folder = new File(dataFolder, "known-alloy-recipes"); | ||
| if (!folder.exists()) { | ||
| folder.mkdirs(); | ||
| } | ||
| } | ||
|
|
||
| public static void init(KnownAlloyRecipes known) { | ||
| instance = known; | ||
| } | ||
|
|
||
| public static KnownAlloyRecipes get() { | ||
| return instance; | ||
| } | ||
|
|
||
| /** Called for every successful forge (not scrap). No-op before the plugin has set an instance. */ | ||
| public static void learn(UUID playerUuid, AlloyRecipe recipe) { | ||
| if (instance != null && playerUuid != null && recipe != null) { | ||
| instance.add(playerUuid, recipe.comboKey()); | ||
| } | ||
| } | ||
|
|
||
| public boolean knows(UUID playerUuid, Alloy alloy) { | ||
| if (playerUuid == null || alloy == null || alloy.getData() == null) { | ||
| return false; | ||
| } | ||
| AlloyRecipe recipe = alloy.getData().getRecipe(); | ||
| return recipe != null && load(playerUuid).contains(recipe.comboKey()); | ||
| } | ||
|
|
||
| private void add(UUID playerUuid, String comboKey) { | ||
| Set<String> known = load(playerUuid); | ||
| if (known.add(comboKey) && !save(playerUuid, known)) { | ||
| // Not on disk, so the next forge of this combo tries again. | ||
| known.remove(comboKey); | ||
| } | ||
| } | ||
|
|
||
| private Set<String> load(UUID playerUuid) { | ||
| Set<String> known = cache.get(playerUuid); | ||
| if (known != null) { | ||
| return known; | ||
| } | ||
| known = new HashSet<>(); | ||
| File file = file(playerUuid); | ||
| if (file.exists()) { | ||
| try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) { | ||
| Object parsed = new JSONParser().parse(reader); | ||
| if (parsed instanceof JSONArray array) { | ||
| for (Object entry : array) { | ||
| if (entry != null && !entry.toString().isBlank()) { | ||
| known.add(entry.toString().trim().toLowerCase(Locale.ROOT)); | ||
| } | ||
| } | ||
| } | ||
| } catch (Exception ex) { | ||
| // Leave the file for staff to repair; this session works from memory only. | ||
| AdvancedCrafting.plugin.getLogger().warning("AC: could not read " + file.getPath() + ", leaving it unchanged: " | ||
| + ex.getMessage()); | ||
| unreadable.add(playerUuid); | ||
| cache.put(playerUuid, known); | ||
| return known; | ||
| } | ||
| } else if (seedFromForgeHistory(playerUuid, known)) { | ||
| save(playerUuid, known); | ||
| } | ||
| cache.put(playerUuid, known); | ||
| return known; | ||
| } | ||
|
|
||
| /** Recipes of the alloys this player forged before recipes were recorded. */ | ||
| private boolean seedFromForgeHistory(UUID playerUuid, Set<String> known) { | ||
| PlayerAlloyForgeTracker tracker = CraftLifecycle.getTracker(); | ||
| if (tracker == null) { | ||
| return false; | ||
| } | ||
| for (String alloyId : tracker.getForgedIds(playerUuid)) { | ||
| Alloy alloy = AlloyManager.getAlloyById(alloyId); | ||
| if (alloy != null && alloy.getData() != null && alloy.getData().getRecipe() != null) { | ||
| known.add(alloy.getData().getRecipe().comboKey()); | ||
| } | ||
| } | ||
| return !known.isEmpty(); | ||
| } | ||
|
|
||
| /** Writes a temp file and moves it over the old one, so a crash can't leave half a file. */ | ||
| @SuppressWarnings("unchecked") | ||
| private boolean save(UUID playerUuid, Set<String> known) { | ||
| if (unreadable.contains(playerUuid)) { | ||
| return true; | ||
| } | ||
| List<String> sorted = new ArrayList<>(known); | ||
| sorted.sort(null); | ||
| JSONArray array = new JSONArray(); | ||
| array.addAll(sorted); | ||
| Path target = file(playerUuid).toPath(); | ||
| Path temp = target.resolveSibling(target.getFileName() + ".tmp"); | ||
| try { | ||
| Files.createDirectories(folder.toPath()); | ||
| Files.writeString(temp, array.toJSONString(), StandardCharsets.UTF_8); | ||
| try { | ||
| Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); | ||
| } catch (AtomicMoveNotSupportedException ex) { | ||
| Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); | ||
| } | ||
| return true; | ||
| } catch (IOException ex) { | ||
| AdvancedCrafting.plugin.getLogger().warning("AC: could not save known alloy recipes for " + playerUuid | ||
| + ": " + ex.getMessage()); | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| private File file(UUID playerUuid) { | ||
| return new File(folder, playerUuid + ".json"); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
142 changes: 142 additions & 0 deletions
142
src/main/java/net/tfminecraft/advancedcrafting/managers/AlloyRecipeCommand.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,142 @@ | ||
| package net.tfminecraft.advancedcrafting.managers; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.TreeSet; | ||
|
|
||
| import org.apache.commons.lang.WordUtils; | ||
| import org.bukkit.entity.Player; | ||
| import org.bukkit.inventory.ItemStack; | ||
|
|
||
| import net.kyori.adventure.text.Component; | ||
| import net.kyori.adventure.text.event.ClickEvent; | ||
| import net.kyori.adventure.text.event.HoverEvent; | ||
| import net.kyori.adventure.text.format.NamedTextColor; | ||
| import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; | ||
| import net.tfminecraft.advancedcrafting.AdvancedCrafting; | ||
| import net.tfminecraft.advancedcrafting.lifecycle.KnownAlloyRecipes; | ||
| import net.tfminecraft.advancedcrafting.loaders.IngredientLoader; | ||
| import net.tfminecraft.advancedcrafting.objects.alloys.Alloy; | ||
| import net.tfminecraft.advancedcrafting.objects.data.AlloyRecipe; | ||
| import net.tfminecraft.advancedcrafting.objects.ingredients.Ingredient; | ||
| import net.tfminecraft.advancedcrafting.utils.AcItemTags; | ||
|
|
||
| /** | ||
| * {@code /alloy recipes} and {@code /alloy recipe [name]}: the base and catalysts of the alloys a | ||
| * player has forged. Only the ingredients are shown, never hits, stats or forge odds. An alloy the | ||
| * player has not forged gets the same reply whether or not it exists, so names can't be probed. | ||
| */ | ||
| final class AlloyRecipeCommand { | ||
| private static final LegacyComponentSerializer LEGACY = LegacyComponentSerializer.legacySection(); | ||
|
|
||
| /** {@code /alloy recipes}: every alloy this account has forged, each name clickable. */ | ||
| void list(Player p) { | ||
| List<Alloy> known = knownAlloys(p); | ||
| if (known.isEmpty()) { | ||
| p.sendMessage("§7You haven't forged any alloys yet. Forge one to keep its recipe here."); | ||
| return; | ||
| } | ||
| p.sendMessage("§6Alloys you have forged §7(" + known.size() + ")§6, click one for its recipe:"); | ||
| Component line = Component.empty(); | ||
| for (int i = 0; i < known.size(); i++) { | ||
| Alloy alloy = known.get(i); | ||
| if (i > 0) { | ||
| line = line.append(Component.text(", ", NamedTextColor.GRAY)); | ||
| } | ||
| line = line.append(LEGACY.deserialize(alloy.getName()) | ||
| .clickEvent(ClickEvent.runCommand("/alloy recipe " + alloy.getId())) | ||
| .hoverEvent(HoverEvent.showText(Component.text("Show the recipe", NamedTextColor.GRAY)))); | ||
| } | ||
| p.sendMessage(line); | ||
| } | ||
|
|
||
| /** {@code /alloy recipe [name]}: the named alloy, or the alloy in the main hand. */ | ||
| void show(Player p, String[] args) { | ||
| if (args.length < 2) { | ||
| showHeld(p); | ||
| return; | ||
| } | ||
| String typed = String.join(" ", java.util.Arrays.copyOfRange(args, 1, args.length)); | ||
| String id = typed.replace(' ', '_').toLowerCase(Locale.ROOT); | ||
| Alloy alloy = AlloyManager.getAlloyById(id); | ||
| if (alloy == null || !knows(p, alloy)) { | ||
| p.sendMessage("§cYou don't know the recipe for §f" + typed + "§c."); | ||
| return; | ||
| } | ||
| sendRecipe(p, alloy); | ||
| } | ||
|
|
||
| private void showHeld(Player p) { | ||
| ItemStack held = p.getInventory().getItemInMainHand(); | ||
| if (AcItemTags.getKind(held) != AcItemTags.Kind.ALLOY) { | ||
| p.sendMessage("§cHold an alloy, or use §f/alloy recipe <name>§c. §f/alloy recipes §clists the ones you know."); | ||
| return; | ||
| } | ||
| Alloy alloy = AlloyManager.getAlloyById(AcItemTags.getId(held)); | ||
| if (alloy == null || !knows(p, alloy)) { | ||
| String name = held.getItemMeta().hasDisplayName() ? held.getItemMeta().getDisplayName() : "this alloy"; | ||
| p.sendMessage("§cYou don't know the recipe for §f" + name + "§c. Forge it yourself to learn it."); | ||
| return; | ||
| } | ||
| sendRecipe(p, alloy); | ||
| } | ||
|
|
||
| private void sendRecipe(Player p, Alloy alloy) { | ||
| // knows() already required a recipe. | ||
| AlloyRecipe recipe = alloy.getData().getRecipe(); | ||
| // The forge reads this index, so a combo that now makes something else must not be shown. | ||
| String result = AdvancedCrafting.getAlloyRecipeStore().getResultByCombo(recipe.comboKey()); | ||
| if (!alloy.getId().equalsIgnoreCase(result)) { | ||
| p.sendMessage("§cThat recipe no longer makes §f" + alloy.getName() + "§c."); | ||
| return; | ||
| } | ||
| p.sendMessage("§6Recipe for §r" + alloy.getName()); | ||
| p.sendMessage("§7Base: §r" + ingredientName(recipe.getBaseId())); | ||
| List<String> catalysts = new ArrayList<>(); | ||
| for (String id : recipe.getCatalystIds()) { | ||
| catalysts.add(ingredientName(id)); | ||
| } | ||
| p.sendMessage("§7Catalysts: §r" + (catalysts.isEmpty() ? "§fnone" : String.join("§7, §r", catalysts))); | ||
| p.sendMessage("§8Add the base to an alloy forge first, then the catalysts in any order."); | ||
| } | ||
|
|
||
| /** Tab completion for {@code /alloy recipe}: only alloys this player has forged. */ | ||
| List<String> completions(Player p) { | ||
| List<String> ids = new ArrayList<>(); | ||
| for (Alloy alloy : knownAlloys(p)) { | ||
| ids.add(alloy.getId()); | ||
| } | ||
| return ids; | ||
| } | ||
|
|
||
| private List<Alloy> knownAlloys(Player p) { | ||
| List<Alloy> known = new ArrayList<>(); | ||
| for (String id : new TreeSet<>(AlloyManager.getAlloyIds())) { | ||
| Alloy alloy = AlloyManager.getAlloyById(id); | ||
| if (knows(p, alloy)) { | ||
| known.add(alloy); | ||
| } | ||
| } | ||
| return known; | ||
| } | ||
|
|
||
| private boolean knows(Player p, Alloy alloy) { | ||
| KnownAlloyRecipes known = KnownAlloyRecipes.get(); | ||
| return known != null && known.knows(p.getUniqueId(), alloy); | ||
| } | ||
|
|
||
| /** The ingredient's item name with its colour, or its id in title case if the item can't be built. */ | ||
| static String ingredientName(String id) { | ||
| Ingredient ingredient = IngredientLoader.getByString(id); | ||
| if (ingredient != null) { | ||
| try { | ||
| // Ingredient.buildTo always gives the item a display name. | ||
| return ingredient.build().getItemMeta().getDisplayName(); | ||
| } catch (RuntimeException ex) { | ||
| // The item source (MMOItems, ItemsAdder) may be missing; fall back to the id. | ||
| } | ||
| } | ||
| return "§f" + WordUtils.capitalize(id.replace('_', ' ')); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.