diff --git a/CHANGELOG.md b/CHANGELOG.md index f84fde8..711c8e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## 0.9.0 + +Quest chapters. + +- **Quests can open tiers.** `quests.tier-unlock` in `config.yml`: `level` (the default; tiers open by Wranglin' level, as before), `either` (the level, or sooner through a quest) or `quest` (only a quest opens Holler, Yonder and Backcountry; Yard is always open, so nobody is locked out of everything). Messages about a locked critter say which way opens it. +- **New admin commands for quests:** `/mobsquad unlock `, `/mobsquad lock ` and `/mobsquad page `. A quest plugin runs them from the console, for example through BetonQuest's command event. The player is told when a tier or page opens. A quest unlock is saved in the player's file as a `tier` line; older versions skip that line, and older files load with none. +- **Placeholders, if PlaceholderAPI is installed:** `%mobsquad_level%`, `critters`, `pages`, `tier_`, `page_`, `has_` and `best_`, for quest conditions. Only the player's own progress, only while they're online, and nothing about anyone else or where they are. +- MobSquad doesn't link to BetonQuest's code, so it works with any BetonQuest version (the live server runs a 3.3 development build) and with other quest plugins. +- Tested: unit tests (54: every unlock mode, Yard always open, the setting and a bad value, saving and old files, every placeholder and unknown ones). Not run on a server yet: the commands, the PlaceholderAPI registration and a real BetonQuest chapter. No chapters are written yet; they're server content. + ## 0.8.1 - **Pigs, cows, chickens and frogs also glow in their coat.** They have only three looks each, so a look repeats for three or four coats; now they also glow in the coat's color and leave its trail, so every coat looks different. Wolves and cats keep the variant only. The list is `glow-too` in `coats.yml`. A copy of `coats.yml` already in `plugins/MobSquad` without that line gets the built-in list. A name that isn't a variant critter is skipped with a warning. diff --git a/README.md b/README.md index 943a573..fd1007d 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Coax mobs into critters for Paper: they follow you, fight only hostile mobs, and live safely in a shared Bunkhouse. No client mods. Gotta coax em all... Pokemob! -**Status:** 0.8.1. Spirit coats; in 0.8.1 pigs, cows, chickens and frogs also glow and worlds can be set to no glow, checked by unit tests only so far. 0.8.0 passed with bots on throwaway Paper 26.1.2 and 26.2 servers (the full suite, 197 checks each) and on 26.3 (95 checks), then the Bunkhouse and coats parts again on all three after a last small change (43 checks on 26.1.2 and 26.2, 26 on 26.3). On 26.3 the bots can't use blocks, so the Bunkhouse menu, picking a coat in it and everything sent out from it didn't run there; the coats themselves ran, with the sidekick getting critters out. Bots can't crouch where the server sees it, so the creeper and fox puzzles were tested with a test-only stand-in for crouching; real crouching is untested. The daily sidekick roll is covered by unit tests only, since it needs 10 hours out. Nothing has been seen in a real game client yet, so how the glow, the particle trail and the chicken variants look is unchecked. Wolves, cats, pigs, cows and frogs aren't critters yet; only the chicken's variants ran on a server. The AuraSkills and Multiverse checks from 0.6.0 weren't rerun. +**Status:** 0.9.0. Quest chapters (tier and page unlocks, placeholders), checked by unit tests only so far. 0.8.1: pigs, cows, chickens and frogs also glow and worlds can be set to no glow, also unit tests only. 0.8.0 passed with bots on throwaway Paper 26.1.2 and 26.2 servers (the full suite, 197 checks each) and on 26.3 (95 checks), then the Bunkhouse and coats parts again on all three after a last small change (43 checks on 26.1.2 and 26.2, 26 on 26.3). On 26.3 the bots can't use blocks, so the Bunkhouse menu, picking a coat in it and everything sent out from it didn't run there; the coats themselves ran, with the sidekick getting critters out. Bots can't crouch where the server sees it, so the creeper and fox puzzles were tested with a test-only stand-in for crouching; real crouching is untested. The daily sidekick roll is covered by unit tests only, since it needs 10 hours out. Nothing has been seen in a real game client yet, so how the glow, the particle trail and the chicken variants look is unchecked. Wolves, cats, pigs, cows and frogs aren't critters yet; only the chicken's variants ran on a server. The AuraSkills and Multiverse checks from 0.6.0 weren't rerun. ## What it does @@ -26,6 +26,7 @@ Coax mobs into critters for Paper: they follow you, fight only hostile mobs, and - **Bunkhouses.** An admin marks a vault block as a Bunkhouse. Anyone who right-clicks it sees only their own critters. Click one to send it out or call it back. Critters never exist as items, so they can't be dropped, traded or duplicated. - **Following.** A critter out with you walks after you and steps beside you if it's left more than 24 blocks behind. - **Wranglin'.** Coaxing earns Wranglin' experience. One critter can be out at once, two from level 10 and three from level 25. Mob tiers unlock at levels 1, 10, 25 and 40. +- **Quest chapters.** A quest plugin can open tiers and journal pages. `quests.tier-unlock` in `config.yml` decides how tiers open: `level` (the default, level only), `either` (the level, or sooner through a quest) or `quest` (only a quest opens Holler, Yonder and Backcountry; Yard is always open). A quest runs `/mobsquad unlock ` or `/mobsquad page ` from the console, for example through BetonQuest's command event. With PlaceholderAPI installed, quest conditions can check the player's own progress: `%mobsquad_level%`, `%mobsquad_critters%`, `%mobsquad_pages%`, `%mobsquad_tier_%`, `%mobsquad_page_%`, `%mobsquad_has_%` and `%mobsquad_best_%` (the highest level among that kind, 0 if none). Values are only for online players, and none of them name another player or a place. - **AuraSkills.** If AuraSkills is installed, Wranglin' shows up as one of its skills, with MobSquad's level. MobSquad keeps the level in the player's file and copies it to AuraSkills when it changes and when the player joins, so a level set with AuraSkills' own commands is put back. AuraSkills' XP multipliers and rewards don't apply to Wranglin'. The skill's AuraSkills settings are in `plugins/MobSquad/auraskills`. Without AuraSkills, nothing changes. - **World groups.** With Multiverse-Inventories, critters cross to another inventory group only through the Bunkhouse: crossing sends the ones out with you home, and you can send them out again from a Bunkhouse there. The sidekick comes along, one copy. A block the enderman fetches only goes into your inventory in the world it came from. - **Safety.** A critter never targets or hurts a player, and players can't hurt it. It never changes a block on its own, explodes, burns in the sun or wanders off by teleporting. The two specials that touch blocks go through the server's own checks: the bee's crops grow through the same event as natural growth, and the enderman takes a block only where a block-break check as you passes. Out of health, it's tuckered out: it drops nothing and rests in the Bunkhouse for 5 real minutes. @@ -53,6 +54,8 @@ Settings are in `plugins/MobSquad/config.yml`: worlds where MobSquad is off, the | `/mobsquad xp ` | admins | Sets a player's Wranglin' experience. | | `/mobsquad level ` | admins | Sets every critter of that kind a player has to a level. | | `/mobsquad sidekick ` | admins | Makes a player's critter of that kind their sidekick, or clears it. | +| `/mobsquad unlock ` and `lock` | admins, quests | Opens (or takes back) Holler, Yonder or Backcountry for a player through a quest. | +| `/mobsquad page ` | admins, quests | Opens a critter's journal page and tells the player. | | `/mobsquad reload` | admins | Rereads config.yml. | `/ms` works too. Permissions: `mobsquad.use` (everyone) and `mobsquad.admin` (ops). diff --git a/build.gradle.kts b/build.gradle.kts index 6f12074..c0b27b1 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -3,7 +3,7 @@ plugins { } group = "com.extantape" -version = "0.8.1" +version = "0.9.0" java { toolchain.languageVersion.set(JavaLanguageVersion.of(25)) @@ -12,16 +12,20 @@ java { repositories { mavenCentral() maven("https://repo.papermc.io/repository/maven-public/") + maven("https://repo.extendedclip.com/releases/") } // Built against the oldest supported Paper, so nothing newer than 26.1 sneaks in. val paperApi = "io.papermc.paper:paper-api:26.1.2.build.74-stable" // Optional: Wranglin' as an AuraSkills skill. Reached only when AuraSkills is installed. val auraSkillsApi = "dev.aurelium:auraskills-api-bukkit:2.4.0" +// Optional: placeholders for quest conditions. Reached only when PlaceholderAPI is installed. +val placeholderApi = "me.clip:placeholderapi:2.12.3" dependencies { compileOnly(paperApi) compileOnly(auraSkillsApi) + compileOnly(placeholderApi) testImplementation(paperApi) testImplementation(platform("org.junit:junit-bom:5.11.4")) diff --git a/docs/decisions.md b/docs/decisions.md index 5d1b2d1..3533eed 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -51,6 +51,7 @@ Dated decisions for this repo, newest last. - Pigs, cows, chickens and frogs: "Add glow and trail (Recommended)". They wear their variant and also glow in the coat's color with its trail, so each coat looks different even where the three looks repeat. Wolves and cats keep the variant only. It's the `glow-too` list in `coats.yml` (0.8.1), so an admin can change it. - Magic worlds: "We have two magic worlds…? One adult and one kid one." On Sonoran those are `magic` and `ninos_magic` (both exist there; checked 2026-11-22). Listing them in `spirit-coats.worlds` is a live change and waits for the owner's go. - **No-glow worlds (lead, 2026-11-22, kids first).** The trust-and-safety review found the glow outline shows through walls to everyone tracking the critter in that world, and a coated critter is always near its owner, so in `ninos_magic` it could point to a kid's hidden base. 0.8.1 adds `spirit-coats.no-glow-worlds` (empty by default): coats there keep their variant and trail but get no outline. The outline goes off when the owner enters, before the critter follows; the trail there is sent only within 32 blocks; a no-glow entry that isn't a coat world is warned about at start, since the setting fails open on a typo. The live go request proposes `ninos_magic` there; the owner decides. +- **Quest chapters (0.9.0), lead's design, 2026-11-22, for the owner's say.** The brief: "Quest chapters introduce new mobs and unlock tiers. Without quests, tiers unlock by Wranglin' level alone." MobSquad offers console commands (`unlock`, `lock`, `page`) and PlaceholderAPI values that any quest plugin can use, and doesn't link to BetonQuest's own API, since the live server runs a 3.3 development build whose API can change. `quests.tier-unlock` defaults to `level`, so installing 0.9.0 changes nothing until a server opts in; `quest` keeps Yard open. The chapters themselves are server content, to be written with the narrative designer once the owner picks how tiers should open. - **Live go: glow in both worlds (owner, Simon chat, 2026-11-22), relayed by the chief of staff.** He answered "Go, glow in both worlds"; the option read "Same look everywhere. The glow can give away where a kid is." The question told him the trust-and-safety finding: the outline shows through walls to everyone in that world, and in the kids' world it could lead someone to a kid's hidden base. He chose that look knowing it. The live install sets `spirit-coats.worlds: [magic, ninos_magic]` with no `no-glow-worlds`, after a bot run and a rehearsal on a copy of Sonoran. `no-glow-worlds` stays in the plugin, so listing `ninos_magic` later is a one-line config change and `/mobsquad reload`. ## 2026-11-15 diff --git a/docs/test-audit.md b/docs/test-audit.md index 854961e..1d5f6a7 100644 --- a/docs/test-audit.md +++ b/docs/test-audit.md @@ -74,6 +74,19 @@ Kept by this repo's owning session, per `~/Code/CLAUDE.md`, "Test self-audits". - **Checked by hand:** on MobShowdown, a full run (42/42) and a run interrupted after 45 seconds both left the work folder empty, with no Java left and the test port closed. The other harnesses use the same code. - **Gap skipped:** the suite can't check its own leftovers, because cleanup runs as the process exits. A wrapper that checks after the suite exits would add more machinery than the check is worth here. +## 2026-11-22: quest chapters (0.9.0) + +| Promise | Test | +| --- | --- | +| By default tiers open by level alone; quest unlocks change nothing | unit `levelModeIgnoresQuestsSoNothingChangesByDefault`, `theSettingDefaultsToLevelAndABadValueIsWarnedAbout` (shipped config is `level`) | +| `either`: a quest opens a tier early, the level still works, one tier's quest doesn't open another | unit `eitherModeLetsAQuestOpenATierEarly` | +| `quest`: level alone doesn't open a tier; Yard always open in every mode (fails safe, nobody locked out) | unit `questModeNeedsTheQuestButYardIsAlwaysOpen` | +| Locked messages say how a tier opens | unit `theLockedMessageSaysHowToOpenIt` | +| Quest unlocks are saved; old files load with none; a bad tier line is skipped, never guessed | unit `questUnlocksAreSavedWithThePlayer`, `filesFromBeforeQuestsLoadWithNoneAndABadTierLineIsSkipped` | +| Placeholders give only the player's own progress; unknown ones are left as written | unit `placeholdersReportOnlyThePlayersOwnProgress` | + +**Gaps:** the `unlock`, `lock` and `page` commands and the PlaceholderAPI registration haven't run on a server (no throwaway servers on 2026-11-22); bot checks for them go in with the next bot run. Who may run the commands is `mobsquad.admin`, the same Brigadier `requires` as the other admin commands, which the bot suite already checks for a player without it. A real BetonQuest chapter is untested until one is written. + ## 2026-11-22: spirit coats (0.8.0) | Promise | Test | diff --git a/src/main/java/com/extantape/mobsquad/MobSquadPlugin.java b/src/main/java/com/extantape/mobsquad/MobSquadPlugin.java index 6e81b71..d5d9057 100644 --- a/src/main/java/com/extantape/mobsquad/MobSquadPlugin.java +++ b/src/main/java/com/extantape/mobsquad/MobSquadPlugin.java @@ -85,6 +85,13 @@ public void onEnable() { pm.registerEvents(coats, this); pm.registerEvents(new Safety(squads), this); CoatMenu coatMenu = new CoatMenu(squads); + if (getServer().getPluginManager().getPlugin("PlaceholderAPI") != null) { + try { + if (com.extantape.mobsquad.hook.Placeholders.register(this, squads)) getLogger().info("Quest placeholders (%mobsquad_...%) are registered with PlaceholderAPI."); + } catch (Throwable e) { + getLogger().log(java.util.logging.Level.WARNING, "Couldn't register placeholders with PlaceholderAPI. Quests can still use the /mobsquad unlock and page commands.", e); + } + } Journal journal = new Journal(this, squads); squads.pageOpener((p, s) -> journal.open(p, s, "got")); this.journal = journal; @@ -151,6 +158,19 @@ public void onLoad(EntitiesLoadEvent e) { for (Species s : Species.values()) if (s.id().startsWith(b.getRemainingLowerCase())) b.suggest(s.id()); return b.buildFuture(); }).executes(this::sidekick)))) + // Quest hooks (0.9.0): BetonQuest's command event, or any other quest plugin, runs these from the console. + .then(Commands.literal("unlock").requires(src -> src.getSender().hasPermission("mobsquad.admin")) + .then(Commands.argument("player", ArgumentTypes.player()) + .then(Commands.argument("tier", StringArgumentType.word()).suggests(this::suggestTiers).executes(c -> unlock(c, true))))) + .then(Commands.literal("lock").requires(src -> src.getSender().hasPermission("mobsquad.admin")) + .then(Commands.argument("player", ArgumentTypes.player()) + .then(Commands.argument("tier", StringArgumentType.word()).suggests(this::suggestTiers).executes(c -> unlock(c, false))))) + .then(Commands.literal("page").requires(src -> src.getSender().hasPermission("mobsquad.admin")) + .then(Commands.argument("player", ArgumentTypes.player()) + .then(Commands.argument("critter", StringArgumentType.word()).suggests((c, b) -> { + for (Species s : Species.values()) if (s.id().startsWith(b.getRemainingLowerCase())) b.suggest(s.id()); + return b.buildFuture(); + }).executes(this::page)))) .then(Commands.literal("reload").requires(src -> src.getSender().hasPermission("mobsquad.admin")).executes(this::reload)) .build(), "Your critters, the dinnerbell, and admin tools for Bunkhouses.", List.of("ms"))); @@ -224,8 +244,8 @@ private int hints(CommandContext c) { int level = c.getSource().getExecutor() instanceof Player p ? squads.wranglinLevel(p) : 100; say(c, "How to coax them (Wranglin' level " + level + "):", NamedTextColor.GOLD); for (Species s : Species.values()) { - boolean open = Levels.unlocked(s.tier, level); - say(c, " " + s.title() + " (" + s.tier.title + "): " + (open ? s.hint : "from Wranglin' level " + s.tier.level + "."), + boolean open = c.getSource().getExecutor() instanceof Player hp ? squads.tierOpen(hp, s.tier) : true; + say(c, " " + s.title() + " (" + s.tier.title + "): " + (open ? s.hint : squads.tierWhen(s.tier) + "."), open ? NamedTextColor.WHITE : NamedTextColor.GRAY); } return Command.SINGLE_SUCCESS; @@ -364,6 +384,64 @@ private int sidekick(CommandContext c) throws CommandSyntaxE return Command.SINGLE_SUCCESS; } + private java.util.concurrent.CompletableFuture suggestTiers( + CommandContext c, com.mojang.brigadier.suggestion.SuggestionsBuilder b) { + for (com.extantape.mobsquad.model.Tier t : com.extantape.mobsquad.model.Tier.values()) { + String id = t.name().toLowerCase(Locale.ROOT); + if (t != com.extantape.mobsquad.model.Tier.YARD && id.startsWith(b.getRemainingLowerCase())) b.suggest(id); + } + return b.buildFuture(); + } + + /** /mobsquad unlock|lock : a quest opens a tier for a player (or an admin takes it back). */ + private int unlock(CommandContext c, boolean open) throws CommandSyntaxException { + Player p = c.getArgument("player", PlayerSelectorArgumentResolver.class).resolve(c.getSource()).getFirst(); + Wrangler w = squads.get(p); + if (w == null) { + say(c, p.getName() + "'s Bunkhouse list can't be read right now; see the server log.", NamedTextColor.RED); + return 0; + } + String name = c.getArgument("tier", String.class); + com.extantape.mobsquad.model.Tier t; + try { + t = com.extantape.mobsquad.model.Tier.valueOf(name.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + t = null; + } + if (t == null || t == com.extantape.mobsquad.model.Tier.YARD) { + say(c, "\"" + name + "\" isn't a tier a quest can open. Use holler, yonder or backcountry.", NamedTextColor.YELLOW); + return 0; + } + boolean changed = open ? w.questTiers.add(t) : w.questTiers.remove(t); + if (changed) squads.save(w); + var mode = squads.settings().tierUnlock(); + String note = mode == com.extantape.mobsquad.model.Unlocks.Mode.LEVEL ? " (quests.tier-unlock is level, so only Wranglin' level counts right now)" : ""; + say(c, "[MobSquad] " + p.getName() + (open ? " has the " : " no longer has the ") + t.title + " tier from a quest" + + (changed ? "" : " (no change)") + "." + note, NamedTextColor.GREEN); + if (open && changed && mode != com.extantape.mobsquad.model.Unlocks.Mode.LEVEL) + p.sendMessage(Component.text("The " + t.title + " tier is open! You can coax " + t.title + " critters now. /mobsquad hints says how.", NamedTextColor.GOLD)); + return Command.SINGLE_SUCCESS; + } + + /** /mobsquad page : a quest chapter introduces a critter and opens its journal page. */ + private int page(CommandContext c) throws CommandSyntaxException { + Player p = c.getArgument("player", PlayerSelectorArgumentResolver.class).resolve(c.getSource()).getFirst(); + Wrangler w = squads.get(p); + Species s = Species.byId(c.getArgument("critter", String.class)); + if (w == null) { + say(c, p.getName() + "'s Bunkhouse list can't be read right now; see the server log.", NamedTextColor.RED); + return 0; + } + if (s == null) { + say(c, "\"" + c.getArgument("critter", String.class) + "\" isn't a critter.", NamedTextColor.YELLOW); + return 0; + } + boolean had = w.pages.contains(s); + journal.open(p, s, "quest"); + say(c, "[MobSquad] " + p.getName() + (had ? " already had" : " has") + " the " + s.title().toLowerCase(Locale.ROOT) + "'s page.", NamedTextColor.GREEN); + return Command.SINGLE_SUCCESS; + } + private int reload(CommandContext c) { reloadConfig(); squads.settings(Settings.read(getConfig(), getLogger())); diff --git a/src/main/java/com/extantape/mobsquad/Settings.java b/src/main/java/com/extantape/mobsquad/Settings.java index 4e0b636..5e3ad26 100644 --- a/src/main/java/com/extantape/mobsquad/Settings.java +++ b/src/main/java/com/extantape/mobsquad/Settings.java @@ -6,13 +6,15 @@ import org.bukkit.configuration.file.FileConfiguration; /** The settings in config.yml, read once and checked. */ -public record Settings(Set disabledWorlds, int recoveryMinutes, int coaxXp, Set coatWorlds, Set noGlowWorlds) { +public record Settings(Set disabledWorlds, int recoveryMinutes, int coaxXp, Set coatWorlds, Set noGlowWorlds, + com.extantape.mobsquad.model.Unlocks.Mode tierUnlock) { public static Settings read(FileConfiguration c, Logger log) { Settings s = new Settings(new HashSet<>(c.getStringList("disabled-worlds")), clamp(c.getInt("recovery-minutes", 5), 0, 1440, "recovery-minutes", log), clamp(c.getInt("coax-xp", 100), 0, 100000, "coax-xp", log), new HashSet<>(c.getStringList("spirit-coats.worlds")), - new HashSet<>(c.getStringList("spirit-coats.no-glow-worlds"))); + new HashSet<>(c.getStringList("spirit-coats.no-glow-worlds")), + tierUnlock(c.getString("quests.tier-unlock", "level"), log)); for (String w : s.noGlowWorlds) if (!s.coatWorlds.contains(w)) log.warning("spirit-coats.no-glow-worlds lists \"" + w + "\", which isn't under spirit-coats.worlds. Check the spelling: a world that's misspelled there gets the glow."); @@ -37,6 +39,13 @@ public boolean glowIn(String world) { return !noGlowWorlds.contains(world); } + static com.extantape.mobsquad.model.Unlocks.Mode tierUnlock(String v, Logger log) { + var m = com.extantape.mobsquad.model.Unlocks.Mode.parse(v); + if (m != null) return m; + log.warning("quests.tier-unlock must be level, either or quest, not \"" + v + "\". Using level."); + return com.extantape.mobsquad.model.Unlocks.Mode.LEVEL; + } + static int clamp(int v, int min, int max, String key, Logger log) { if (v >= min && v <= max) return v; int to = Math.max(min, Math.min(max, v)); diff --git a/src/main/java/com/extantape/mobsquad/Squads.java b/src/main/java/com/extantape/mobsquad/Squads.java index 29c4885..4dfb6e2 100644 --- a/src/main/java/com/extantape/mobsquad/Squads.java +++ b/src/main/java/com/extantape/mobsquad/Squads.java @@ -116,6 +116,18 @@ public com.extantape.mobsquad.hook.WranglinSkill skill() { return skill; } + /** Whether this player may coax and send out critters of a tier, by level and quests as config says. */ + public boolean tierOpen(Player p, com.extantape.mobsquad.model.Tier tier) { + Wrangler w = get(p); + return com.extantape.mobsquad.model.Unlocks.open(settings.tierUnlock(), tier, wranglinLevel(p), + w == null ? java.util.Set.of() : w.questTiers); + } + + /** When a locked tier opens, to finish a sentence ("from Wranglin' level 25"). */ + public String tierWhen(com.extantape.mobsquad.model.Tier tier) { + return com.extantape.mobsquad.model.Unlocks.when(settings.tierUnlock(), tier); + } + public int wranglinLevel(Player p) { Wrangler w = get(p); return w == null ? 1 : Levels.level(w.wranglinXp); @@ -224,7 +236,7 @@ public void keepSidekicks() { if (w == null || w.sidekick == null || posse.isOut(w.sidekick)) continue; Critter c = w.find(w.sidekick); if (c == null || c.resting(now) || p.isDead() || p.getGameMode() == org.bukkit.GameMode.SPECTATOR) continue; - if (!settings.enabledIn(p.getWorld().getName()) || !p.hasPermission("mobsquad.use") || !Levels.unlocked(c.species().tier, wranglinLevel(p))) continue; + if (!settings.enabledIn(p.getWorld().getName()) || !p.hasPermission("mobsquad.use") || !tierOpen(p, c.species().tier)) continue; posse.send(p, c); p.sendActionBar(Component.text(c.name() + " is at your side.", NamedTextColor.GOLD)); } diff --git a/src/main/java/com/extantape/mobsquad/coax/Coaxing.java b/src/main/java/com/extantape/mobsquad/coax/Coaxing.java index 1317617..97307a1 100644 --- a/src/main/java/com/extantape/mobsquad/coax/Coaxing.java +++ b/src/main/java/com/extantape/mobsquad/coax/Coaxing.java @@ -90,8 +90,8 @@ public void onClick(PlayerInteractEntityEvent event) { : mob.isLeashed() ? "That " + what + "'s on a lead. It belongs to somebody already." : mob.isInsideVehicle() || !mob.getPassengers().isEmpty() ? "That " + what + "'s busy." : on(mob) != null ? "Somebody's already coaxing that " + what + "." - : !Levels.unlocked(puzzle.species().tier, level) ? "A " + what + " is a " + puzzle.species().tier.title - + " critter. You can coax one from Wranglin' level " + puzzle.species().tier.level + "." + : !squads.tierOpen(p, puzzle.species().tier) ? "A " + what + " is a " + puzzle.species().tier.title + + " critter. You can coax one " + squads.tierWhen(puzzle.species().tier) + "." : squads.get(p) == null ? "Your Bunkhouse list can't be read right now. Ask an admin to check the server log." : puzzle.refuse(p, mob); if (refusal != null) { diff --git a/src/main/java/com/extantape/mobsquad/hook/Placeholders.java b/src/main/java/com/extantape/mobsquad/hook/Placeholders.java new file mode 100644 index 0000000..06b6364 --- /dev/null +++ b/src/main/java/com/extantape/mobsquad/hook/Placeholders.java @@ -0,0 +1,81 @@ +package com.extantape.mobsquad.hook; + +import com.extantape.mobsquad.Squads; +import com.extantape.mobsquad.model.Critter; +import com.extantape.mobsquad.model.Species; +import com.extantape.mobsquad.model.Tier; +import com.extantape.mobsquad.model.Wrangler; +import java.util.Locale; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; + +/** + * PlaceholderAPI values about the player they're asked for, so a quest plugin (BetonQuest's placeholder conditions, for + * one) can check progress. Only online players have values; anyone else gets an empty string. Nothing here names + * another player or says where anyone is. See {@link PlaceholderValues} for the list. + */ +public final class Placeholders extends PlaceholderExpansion { + private final Plugin plugin; + private final Squads squads; + + private Placeholders(Plugin plugin, Squads squads) { + this.plugin = plugin; + this.squads = squads; + } + + /** Registers the placeholders. Call only when PlaceholderAPI is installed. */ + public static boolean register(Plugin plugin, Squads squads) { + return new Placeholders(plugin, squads).register(); + } + + @Override public String getIdentifier() { return "mobsquad"; } + @Override public String getAuthor() { return "EXTANT APE"; } + @Override public String getVersion() { return plugin.getPluginMeta().getVersion(); } + @Override public boolean persist() { return true; } + + @Override + public String onRequest(OfflinePlayer who, String params) { + if (!(who instanceof Player p) || !p.isOnline()) return ""; + Wrangler w = squads.get(p); + if (w == null) return ""; + return PlaceholderValues.value(params, squads.wranglinLevel(p), w, t -> squads.tierOpen(p, t)); + } + + /** The values, kept apart from PlaceholderAPI so they can be unit tested. */ + public static final class PlaceholderValues { + private PlaceholderValues() {} + + /** + * level: Wranglin' level. critters, pages: how many. tier_holler (and yonder, backcountry, yard): true or false, + * open now by level and quests. page_creeper: true if that journal page is open. has_creeper: true if the player + * has one. best_creeper: the highest level among their creepers, 0 if none. Anything else is null, which + * PlaceholderAPI leaves as written. + */ + public static String value(String params, int level, Wrangler w, java.util.function.Predicate tierOpen) { + String k = params.toLowerCase(Locale.ROOT); + switch (k) { + case "level": return Integer.toString(level); + case "critters": return Integer.toString(w.critters.size()); + case "pages": return Integer.toString(w.pages.size()); + default: break; + } + int u = k.indexOf('_'); + if (u < 0) return null; + String kind = k.substring(0, u), arg = k.substring(u + 1); + if (kind.equals("tier")) { + for (Tier t : Tier.values()) if (t.name().equalsIgnoreCase(arg)) return Boolean.toString(tierOpen.test(t)); + return null; + } + Species s = Species.byId(arg); + if (s == null) return null; + return switch (kind) { + case "page" -> Boolean.toString(w.pages.contains(s)); + case "has" -> Boolean.toString(w.critters.stream().anyMatch(c -> c.species() == s)); + case "best" -> Integer.toString(w.critters.stream().filter(c -> c.species() == s).mapToInt(Critter::level).max().orElse(0)); + default -> null; + }; + } + } +} diff --git a/src/main/java/com/extantape/mobsquad/model/Unlocks.java b/src/main/java/com/extantape/mobsquad/model/Unlocks.java new file mode 100644 index 0000000..9182e6c --- /dev/null +++ b/src/main/java/com/extantape/mobsquad/model/Unlocks.java @@ -0,0 +1,50 @@ +package com.extantape.mobsquad.model; + +import java.util.Locale; +import java.util.Set; + +/** + * How a player's tiers open. The brief: quest chapters introduce new mobs and unlock tiers; without quests, tiers unlock + * by Wranglin' level alone. A server picks one of three ways in config ({@code quests.tier-unlock}): + *
    + *
  • {@code level} (the default): Wranglin' level only, as before quests existed. Quest unlocks are kept but unused.
  • + *
  • {@code either}: the level, or a quest that unlocked the tier early.
  • + *
  • {@code quest}: only a quest opens a tier above Yard. Yard is always open, so nobody is ever locked out of everything.
  • + *
+ */ +public final class Unlocks { + public enum Mode { + LEVEL, EITHER, QUEST; + + /** Reads a config value; anything else is null, so the caller can warn and keep the default. */ + public static Mode parse(String s) { + if (s == null) return null; + try { + return valueOf(s.strip().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + return null; + } + } + } + + private Unlocks() {} + + public static boolean open(Mode mode, Tier tier, int level, Set quested) { + if (tier == Tier.YARD) return true; + boolean byLevel = Levels.unlocked(tier, level), byQuest = quested.contains(tier); + return switch (mode) { + case LEVEL -> byLevel; + case EITHER -> byLevel || byQuest; + case QUEST -> byQuest; + }; + } + + /** When a locked tier opens, to finish a sentence such as "You can coax one ...". */ + public static String when(Mode mode, Tier tier) { + return switch (mode) { + case LEVEL -> "from Wranglin' level " + tier.level; + case EITHER -> "from Wranglin' level " + tier.level + ", or sooner through a quest"; + case QUEST -> "once a quest opens the " + tier.title + " tier"; + }; + } +} diff --git a/src/main/java/com/extantape/mobsquad/model/Wrangler.java b/src/main/java/com/extantape/mobsquad/model/Wrangler.java index d857ff5..6530935 100644 --- a/src/main/java/com/extantape/mobsquad/model/Wrangler.java +++ b/src/main/java/com/extantape/mobsquad/model/Wrangler.java @@ -14,6 +14,8 @@ public final class Wrangler { public UUID sidekick; public long sidekickRoll; public final java.util.Set pages = java.util.EnumSet.noneOf(Species.class); + /** Tiers a quest has unlocked for this player (0.9.0). Used when quests.tier-unlock is either or quest. */ + public final java.util.Set questTiers = java.util.EnumSet.noneOf(Tier.class); public Wrangler(UUID player) { this.player = player; diff --git a/src/main/java/com/extantape/mobsquad/store/Store.java b/src/main/java/com/extantape/mobsquad/store/Store.java index a4abe63..4056442 100644 --- a/src/main/java/com/extantape/mobsquad/store/Store.java +++ b/src/main/java/com/extantape/mobsquad/store/Store.java @@ -20,12 +20,13 @@ * wranglin 150 * critter 6b1f... chicken 1 0 0 Clucky * page chicken + * tier yonder * sidekick 6b1f... * sidekick-roll 20407 * * * A critter line is its id, species, level, experience, when it's rested (epoch milliseconds, 0 when ready) and its - * name, URL-encoded, then its minutes out with its owner (missing in files from before 0.5.0, read as 0), then the spirit coat its owner picked, 0 to 10 (missing in files from before 0.8.0, read as 0, which wears the newest earned). A page line is a La Ménagerie page the player has opened; owning a critter opens its page too. Written to a temporary file and moved into place, so a crash leaves the old file or the new one. + * name, URL-encoded, then its minutes out with its owner (missing in files from before 0.5.0, read as 0), then the spirit coat its owner picked, 0 to 10 (missing in files from before 0.8.0, read as 0, which wears the newest earned). A page line is a La Ménagerie page the player has opened; owning a critter opens its page too. A tier line is a tier a quest unlocked (0.9.0); older versions skip it. Written to a temporary file and moved into place, so a crash leaves the old file or the new one. * Lines that can't be read are skipped and counted, never guessed at. */ public final class Store { @@ -61,6 +62,7 @@ public Loaded load(UUID player) throws IOException { } case "sidekick" -> w.sidekick = UUID.fromString(p[1]); case "sidekick-roll" -> w.sidekickRoll = Long.parseLong(p[1]); + case "tier" -> w.questTiers.add(com.extantape.mobsquad.model.Tier.valueOf(p[1].toUpperCase(java.util.Locale.ROOT))); case "page" -> { Species s = Species.byId(p[1]); if (s == null) throw new IllegalArgumentException(); @@ -99,6 +101,7 @@ public void save(Wrangler w) throws IOException { if (w.sidekick != null) sb.append("sidekick ").append(w.sidekick).append('\n'); if (w.sidekickRoll > 0) sb.append("sidekick-roll ").append(w.sidekickRoll).append('\n'); for (Species s : w.pages) sb.append("page ").append(s.id()).append('\n'); + for (com.extantape.mobsquad.model.Tier t : w.questTiers) sb.append("tier ").append(t.name().toLowerCase(java.util.Locale.ROOT)).append('\n'); Path tmp = dir.resolve(w.player + ".txt.tmp"); Files.writeString(tmp, sb.toString(), StandardCharsets.UTF_8); Files.move(tmp, file(w.player), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE); diff --git a/src/main/java/com/extantape/mobsquad/world/BunkhouseMenu.java b/src/main/java/com/extantape/mobsquad/world/BunkhouseMenu.java index d168508..f136d6c 100644 --- a/src/main/java/com/extantape/mobsquad/world/BunkhouseMenu.java +++ b/src/main/java/com/extantape/mobsquad/world/BunkhouseMenu.java @@ -223,8 +223,8 @@ String whyNot(Player p, Critter c) { long now = System.currentTimeMillis(); if (c.resting(now)) return c.name() + " is still resting."; int level = squads.wranglinLevel(p); - if (!Levels.unlocked(c.species().tier, level)) - return c.name() + " is a " + c.species().tier.title + " critter. It can go out from Wranglin' level " + c.species().tier.level + "."; + if (!squads.tierOpen(p, c.species().tier)) + return c.name() + " is a " + c.species().tier.title + " critter. It can go out " + squads.tierWhen(c.species().tier) + "."; int max = Levels.posse(level); if (squads.posse().counted(p.getUniqueId()) >= max) return "You can have " + max + (max == 1 ? " critter" : " critters") + " out at once at Wranglin' level " + level + ". Call one back first."; diff --git a/src/main/java/com/extantape/mobsquad/world/Vittles.java b/src/main/java/com/extantape/mobsquad/world/Vittles.java index 639baf3..f96de26 100644 --- a/src/main/java/com/extantape/mobsquad/world/Vittles.java +++ b/src/main/java/com/extantape/mobsquad/world/Vittles.java @@ -93,7 +93,7 @@ public void onUse(PlayerInteractEvent event) { p.playSound(p.getLocation(), Sound.ENTITY_GENERIC_EAT, 0.8f, 1.3f); int max = Levels.posse(squads.wranglinLevel(p)); boolean room = squads.settings().enabledIn(p.getWorld().getName()) && squads.posse().counted(p.getUniqueId()) < max - && Levels.unlocked(ready.species().tier, squads.wranglinLevel(p)); + && squads.tierOpen(p, ready.species().tier); if (room) { Posse.Out o = squads.posse().send(p, ready); o.mob().getWorld().spawnParticle(Particle.HAPPY_VILLAGER, o.mob().getLocation().add(0, 0.6, 0), 8, 0.4, 0.4, 0.4); diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 7a9a836..7077488 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -19,3 +19,13 @@ coax-xp: 100 spirit-coats: worlds: [] no-glow-worlds: [] + +# Quest chapters (0.9.0). How a player's tiers open: +# level Wranglin' level only (the default, as before quests). +# either the level, or sooner when a quest runs /mobsquad unlock . +# quest only a quest opens Holler, Yonder and Backcountry. Yard is always open. +# Quests (BetonQuest's command event, or any quest plugin) can also run /mobsquad page to open a +# journal page, and with PlaceholderAPI check %mobsquad_level%, %mobsquad_tier_yonder%, %mobsquad_has_fox% and the +# others listed in the README. +quests: + tier-unlock: level diff --git a/src/main/resources/paper-plugin.yml b/src/main/resources/paper-plugin.yml index cea4f8f..2b64138 100644 --- a/src/main/resources/paper-plugin.yml +++ b/src/main/resources/paper-plugin.yml @@ -4,13 +4,18 @@ main: com.extantape.mobsquad.MobSquadPlugin api-version: '26.1' description: "Coax mobs into critters that follow you, fight only hostile mobs and rest in a Bunkhouse. Gotta coax em all... Pokemob!" website: https://github.com/ExtantApe/MobSquad -# Optional: with AuraSkills installed, Wranglin' is an AuraSkills skill. +# Optional: with AuraSkills installed, Wranglin' is an AuraSkills skill. With PlaceholderAPI, quests can check +# %mobsquad_...% placeholders. dependencies: server: AuraSkills: load: BEFORE required: false join-classpath: true + PlaceholderAPI: + load: BEFORE + required: false + join-classpath: true # Commands are registered with Brigadier in code, so there is no commands section. permissions: mobsquad.use: diff --git a/src/test/java/com/extantape/mobsquad/QuestTest.java b/src/test/java/com/extantape/mobsquad/QuestTest.java new file mode 100644 index 0000000..817b3fc --- /dev/null +++ b/src/test/java/com/extantape/mobsquad/QuestTest.java @@ -0,0 +1,131 @@ +package com.extantape.mobsquad; + +import static org.junit.jupiter.api.Assertions.*; + +import com.extantape.mobsquad.hook.Placeholders.PlaceholderValues; +import com.extantape.mobsquad.model.Critter; +import com.extantape.mobsquad.model.Species; +import com.extantape.mobsquad.model.Tier; +import com.extantape.mobsquad.model.Unlocks; +import com.extantape.mobsquad.model.Unlocks.Mode; +import com.extantape.mobsquad.model.Wrangler; +import com.extantape.mobsquad.store.Store; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.logging.Handler; +import java.util.logging.LogRecord; +import java.util.logging.Logger; +import org.bukkit.configuration.file.YamlConfiguration; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Quest chapters (0.9.0): how tiers open, the saved quest unlocks, the setting and the placeholders. */ +class QuestTest { + @Test + void levelModeIgnoresQuestsSoNothingChangesByDefault() { + Set quested = EnumSet.of(Tier.YONDER); + assertFalse(Unlocks.open(Mode.LEVEL, Tier.YONDER, 24, quested), "a quest unlock doesn't count in level mode"); + assertTrue(Unlocks.open(Mode.LEVEL, Tier.YONDER, 25, Set.of())); + } + + @Test + void eitherModeLetsAQuestOpenATierEarly() { + assertTrue(Unlocks.open(Mode.EITHER, Tier.YONDER, 1, EnumSet.of(Tier.YONDER))); + assertTrue(Unlocks.open(Mode.EITHER, Tier.YONDER, 25, Set.of()), "the level still works"); + assertFalse(Unlocks.open(Mode.EITHER, Tier.BACKCOUNTRY, 39, EnumSet.of(Tier.YONDER)), "one tier's quest doesn't open another"); + } + + @Test + void questModeNeedsTheQuestButYardIsAlwaysOpen() { + assertFalse(Unlocks.open(Mode.QUEST, Tier.HOLLER, 100, Set.of()), "level alone doesn't open a tier in quest mode"); + assertTrue(Unlocks.open(Mode.QUEST, Tier.HOLLER, 1, EnumSet.of(Tier.HOLLER))); + for (Mode m : Mode.values()) assertTrue(Unlocks.open(m, Tier.YARD, 1, Set.of()), "Yard is open in " + m + " mode, so nobody is locked out of everything"); + } + + @Test + void theLockedMessageSaysHowToOpenIt() { + assertEquals("from Wranglin' level 25", Unlocks.when(Mode.LEVEL, Tier.YONDER)); + assertTrue(Unlocks.when(Mode.EITHER, Tier.YONDER).contains("quest")); + assertEquals("once a quest opens the Yonder tier", Unlocks.when(Mode.QUEST, Tier.YONDER)); + } + + static final class Warnings extends Handler { + final List messages = new ArrayList<>(); + @Override public void publish(LogRecord r) { messages.add(r.getMessage()); } + @Override public void flush() {} + @Override public void close() {} + } + + @Test + void theSettingDefaultsToLevelAndABadValueIsWarnedAbout() throws Exception { + Logger log = Logger.getAnonymousLogger(); log.setUseParentHandlers(false); Warnings warn = new Warnings(); log.addHandler(warn); + assertEquals(Mode.LEVEL, Settings.read(new YamlConfiguration(), log).tierUnlock()); + YamlConfiguration y = new YamlConfiguration(); + y.set("quests.tier-unlock", "Either"); + assertEquals(Mode.EITHER, Settings.read(y, log).tierUnlock(), "case doesn't matter"); + y.set("quests.tier-unlock", "sometimes"); + assertEquals(Mode.LEVEL, Settings.read(y, log).tierUnlock()); + assertEquals(1, warn.messages.size(), "a bad value is warned about: " + warn.messages); + YamlConfiguration bundled = new YamlConfiguration(); + try (InputStream in = QuestTest.class.getResourceAsStream("/config.yml")) { + bundled.loadFromString(new String(in.readAllBytes(), StandardCharsets.UTF_8)); + } + assertEquals("level", bundled.getString("quests.tier-unlock"), "the shipped config keeps tiers on level alone"); + } + + @Test + void questUnlocksAreSavedWithThePlayer(@TempDir Path dir) throws Exception { + Store store = new Store(dir); + UUID p = UUID.randomUUID(); + Wrangler w = new Wrangler(p); + w.questTiers.add(Tier.HOLLER); + w.questTiers.add(Tier.BACKCOUNTRY); + store.save(w); + Store.Loaded back = store.load(p); + assertEquals(0, back.skipped()); + assertEquals(EnumSet.of(Tier.HOLLER, Tier.BACKCOUNTRY), back.wrangler().questTiers); + } + + @Test + void filesFromBeforeQuestsLoadWithNoneAndABadTierLineIsSkipped(@TempDir Path dir) throws Exception { + UUID p = UUID.randomUUID(); + Files.writeString(dir.resolve(p + ".txt"), "wranglin 10\npage chicken\n"); + assertTrue(new Store(dir).load(p).wrangler().questTiers.isEmpty()); + UUID q = UUID.randomUUID(); + Files.writeString(dir.resolve(q + ".txt"), "wranglin 10\ntier dragon\ntier yonder\n"); + Store.Loaded l = new Store(dir).load(q); + assertEquals(1, l.skipped()); + assertEquals(EnumSet.of(Tier.YONDER), l.wrangler().questTiers); + } + + @Test + void placeholdersReportOnlyThePlayersOwnProgress() { + Wrangler w = new Wrangler(UUID.randomUUID()); + w.critters.add(new Critter(UUID.randomUUID(), Species.CHICKEN, "Clucky", 12, 0, 0, 0)); + w.critters.add(new Critter(UUID.randomUUID(), Species.CHICKEN, "Pecky", 30, 0, 0, 0)); + w.pages.add(Species.CHICKEN); + w.pages.add(Species.FOX); + var open = (java.util.function.Predicate) t -> t == Tier.YARD || t == Tier.HOLLER; + assertEquals("14", PlaceholderValues.value("level", 14, w, open)); + assertEquals("2", PlaceholderValues.value("critters", 14, w, open)); + assertEquals("2", PlaceholderValues.value("pages", 14, w, open)); + assertEquals("true", PlaceholderValues.value("tier_holler", 14, w, open)); + assertEquals("false", PlaceholderValues.value("TIER_Yonder", 14, w, open), "case doesn't matter"); + assertEquals("true", PlaceholderValues.value("page_fox", 14, w, open)); + assertEquals("false", PlaceholderValues.value("page_creeper", 14, w, open)); + assertEquals("true", PlaceholderValues.value("has_chicken", 14, w, open)); + assertEquals("false", PlaceholderValues.value("has_fox", 14, w, open), "a page isn't a critter"); + assertEquals("30", PlaceholderValues.value("best_chicken", 14, w, open)); + assertEquals("0", PlaceholderValues.value("best_creeper", 14, w, open)); + assertEquals("false", PlaceholderValues.value("has_iron_golem", 14, w, open), "a critter id with an underscore works"); + for (String bad : new String[] {"tier_dragon", "page_dragon", "where", "has_", "owner_chicken", ""}) + assertNull(PlaceholderValues.value(bad, 14, w, open), bad + " is left as written"); + } +}