Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c776dca248 | ||
|
|
bce5391b70 | ||
|
|
f183d7daaa |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# Fantasy Stick
|
||||
|
||||
**Transferable characters and standalone names (US-001), equipment restoration (US-002), inventory safety (US-003), paginated character inspection (US-005), native session health/defeat (US-006), book parties/native damage protection (US-012), and switch delay (US-023) have automated implementation coverage. The full RPG remains in development and is not deployment-ready.**
|
||||
**Transferable characters, equipment restoration, inventory safety, character inspection, native session health, durable downed decisions and combat Revive, parties, and switch delay have automated implementation coverage. The full RPG remains in development and is not deployment-ready.**
|
||||
|
||||
Fantasy Stick is the proposed transferable-character RPG plugin for Social Minecraft. Its approved design uses Paper character sheets, native equipment storage and a book/basic-stick/seven-ability hotbar. Crafting, native-health offhand sessions, read-only character books and book-managed parties with native damage protection are assembled; active food overrides, stat/ability book actions, combat progression and spells remain incomplete. The server-independent progression core now tests initial stats/points, stat purchases, CON's equal maximum/current-health gain, capped XP and `MAX` presentation. YAML persistence, backend death/revival transitions and a native signed-book factory are also present. Saved-sheet crafting and accepted anvil-name persistence are wired. Stat purchases and spell execution remain incomplete.
|
||||
|
||||
@@ -175,11 +175,13 @@ Offhand entry applies actual native maximum health `min(10 + CON, native health
|
||||
|
||||
Ordinary health, food, saturation, exhaustion and health-display state belong to the holder/session, not the character sheet. The session receipt acknowledges this snapshot before native mutation; versioned player PDC records its application/restoration phase. Voluntary exit restores ordinary gear/vitals at the current location, with ordinary health capped by the current legitimate maximum. Character damage is saved on the worker, and the character claim/receipt cannot complete ahead of that acknowledgment. Quit and disable perform the same best-effort cleanup. Failed or uncertain saves retain the receipt and acknowledged character record instead of permitting a stale-health reentry. Missing/ambiguous native proof never authorizes a snapshot heal; process-owned maximum overrides are still retired independently of equipment/client-write failures.
|
||||
|
||||
An intercepted fantasy defeat records authoritative death once, removes session state, restores ordinary health to its current maximum and attempts return to the entry location. Ordinary health is restored before health-scale setters can send or queue client health packets: cancelled defeat must not deliver zero health and strand an otherwise alive player on a death screen. Refused/failed return leaves the player at the current location with a warning, not an alternate destination or invulnerability. A public red burst marks the defeat location. After the death acknowledgment, guarded conversion replaces the unchanged sheet stack with one signed Tail book. New Tails group ordinary-sized name/level/XP/points/stats on a summary page, then give each learned ability its own section with saved ID, assigned ability slots and cooldown deadline. Unknown IDs, saved unlearned cooldowns, empty abilities and death time stay explicit; long content continues onto additional pages without truncation. No ability descriptions are invented and existing books are not rewritten. Static Unicode-safe Tail pagination survives native serialization without a plugin; signed books use a different codec from the 100-page writable-book format. Stale or ambiguous conversion never overwrites another item or automatically reissues a book.
|
||||
An intercepted active-character lethal outcome now creates one durable downed episode rather than immediately recording death. The episode captures its original session, holder, lethal attribution, downed anchor, entry-return location and absolute deadline. While it remains pending, native damage, healing, movement, displacement, inventory/control changes and ordinary gameplay actions are contained; logout and shutdown restore only safe ordinary-holder state while retaining the original countdown. Reconnect rebinds the same proved session at its saved anchor without resetting time. The bounded death menu can accept death or wait for the learned, aimed, any-party Revive; Phoenix Down remains unavailable until its separate complete capability is delivered.
|
||||
|
||||
Accept Death and timeout compete with Revive for one persisted outcome. Successful Revive saves full current fantasy health, resumes the same active character in place and uses one absolute configurable protection deadline. Final death records the decision time—or the original expiry for delayed offline reconciliation—then applies frozen PvP reward/coin shares and party consequences exactly once before guarded Tail conversion. Ordinary health is restored before health-scale setters can send or queue client health packets, and return uses only the captured session-entry location. Refused or unavailable destinations retain explicit recovery evidence. New Tails retain the existing signed, authoritative death identity and readable static character history; stale or ambiguous conversion never overwrites another item or automatically reissues a book.
|
||||
|
||||
Interrupted recovery requires matching player/session receipt and native proof. It preserves current native modifier ownership and does not resurrect expired effects. Repeated/stale recovery cannot replay ordinary health or recreate an already released claim. This is **not crash-atomic** across player, inventory and plugin files; unresolved native setter phases and unacknowledged progress may require inspection. Legacy equipment-only receipts remain readable but do not grant health-restoration authority. Older binaries do not understand the new optional ordinary-vitals receipt field; do not downgrade across unresolved newer receipts.
|
||||
|
||||
Active hunger/exhaustion suppression and food-regeneration discrimination remain US-026 work. Book stat purchases, XP delivery, basic/learned attacks and Revive remain separate unfinished stories. The preceding equipment/progression checkpoint sections are historical evidence, not the current health scope.
|
||||
The preceding equipment/progression checkpoint sections retain their historical evidence; current downed, Revive, nutrition, progression and combat behavior is governed by their later delivered stories and native integration tests.
|
||||
|
||||
## Character inspection and inventory safety
|
||||
|
||||
|
||||
@@ -60,6 +60,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private games.dmg.fantasystick.shop.RareShopMenus rareShopMenus;
|
||||
private games.dmg.fantasystick.shop.RarePotionService rarePotions;
|
||||
private games.dmg.fantasystick.shop.RareReskillService rareReskills;
|
||||
private games.dmg.fantasystick.shop.RareMagicCoreService rareMagicCores;
|
||||
private org.bukkit.scheduler.BukkitTask rareMarketPulse,rareMenuPulse;
|
||||
private games.dmg.fantasystick.party.PartyCombat partyCombat;
|
||||
private EquipmentAdminCommand admin;
|
||||
@@ -140,6 +141,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
private games.dmg.fantasystick.adventure.FishingDirectory fishing;
|
||||
private games.dmg.fantasystick.adventure.FishingController fishingController;
|
||||
private games.dmg.fantasystick.dungeon.DungeonDirectory dungeons;
|
||||
private games.dmg.fantasystick.session.DownedDirectory downed;
|
||||
private games.dmg.fantasystick.session.DownedController downedController;
|
||||
private games.dmg.fantasystick.persistence.DownedSettings downedSettings;
|
||||
private games.dmg.fantasystick.dungeon.DungeonController dungeonController;
|
||||
private games.dmg.fantasystick.dungeon.DungeonCommands dungeonCommands;
|
||||
private games.dmg.fantasystick.persistence.SheetResourcePackSettings sheetResourcePackSettings;
|
||||
@@ -189,6 +193,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
for (String key : games.dmg.fantasystick.persistence.PartyEconomySettings.keys()) partyEconomyConfiguration.put(key, getConfig().getString(key,games.dmg.fantasystick.persistence.PartyEconomySettings.defaultValue(key)));
|
||||
var gearConfiguration=new java.util.LinkedHashMap<String,String>();for(String key:games.dmg.fantasystick.persistence.GearSettings.keys())gearConfiguration.put(key,getConfig().getString(key,games.dmg.fantasystick.persistence.GearSettings.defaultValue(key)));
|
||||
var rareConfiguration=new java.util.LinkedHashMap<String,String>();for(String key:games.dmg.fantasystick.persistence.RareSettings.keys())rareConfiguration.put(key,getConfig().getString(key,games.dmg.fantasystick.persistence.RareSettings.defaultValue(key)));
|
||||
var downedConfiguration=new java.util.LinkedHashMap<String,String>();for(String key:games.dmg.fantasystick.persistence.DownedSettings.keys())downedConfiguration.put(key,getConfig().getString(key,games.dmg.fantasystick.persistence.DownedSettings.defaultValue(key)));
|
||||
var coinConfiguration = new java.util.LinkedHashMap<String, String>();
|
||||
for (String key : games.dmg.fantasystick.persistence.CoinSettings.keys()) {
|
||||
coinConfiguration.put(key, getConfig().getString(key,
|
||||
@@ -264,6 +269,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
getDataFolder().toPath(), partyEconomyConfiguration);
|
||||
gearSettings=new games.dmg.fantasystick.persistence.GearSettings(getDataFolder().toPath(),gearConfiguration);
|
||||
rareSettings=new games.dmg.fantasystick.persistence.RareSettings(getDataFolder().toPath(),rareConfiguration);
|
||||
downedSettings=new games.dmg.fantasystick.persistence.DownedSettings(getDataFolder().toPath(),downedConfiguration);
|
||||
coinSettings = new games.dmg.fantasystick.persistence.CoinSettings(getDataFolder().toPath(), coinConfiguration);
|
||||
hardMobXpSettings = new games.dmg.fantasystick.persistence.HardMobXpSettings(
|
||||
getDataFolder().toPath(), hardMobXp.toString());
|
||||
@@ -343,6 +349,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
dungeons = new games.dmg.fantasystick.dungeon.DungeonDirectory(
|
||||
new games.dmg.fantasystick.persistence.YamlDungeonRepository(getDataFolder().toPath()),
|
||||
() -> adventureQuestSettings.rules().dungeonRoomLinkDistance());
|
||||
downed = new games.dmg.fantasystick.session.DownedDirectory(getDataFolder().toPath(),Clock.systemUTC());
|
||||
if(adventureRepository.requiresDungeonRewardMigration())adventureQuests.migrateLegacyDungeonRewards(id->dungeons.find(id).flatMap(value->value.rooms().stream().filter(room->room.boss()!=null).findFirst().map(room->new games.dmg.fantasystick.adventure.AdventureQuestDirectory.LegacyDungeonReward(new games.dmg.fantasystick.adventure.AdventureQuestDirectory.Reward(value.completionReward().xp(),value.completionReward().coins()),room.id(),dungeons.runView(id,adventureQuests.snapshot().catalog()==null?new java.util.UUID(0,0):adventureQuests.snapshot().catalog().revision()).map(games.dmg.fantasystick.dungeon.DungeonState.Run::defeated).orElse(false))))).join();
|
||||
armorers=new games.dmg.fantasystick.shop.FantasyArmorerDirectory(new games.dmg.fantasystick.persistence.YamlFantasyArmorerRepository(getDataFolder().toPath()));
|
||||
rareMerchants=new games.dmg.fantasystick.shop.RareMerchantDirectory(new games.dmg.fantasystick.persistence.YamlRareMerchantRepository(getDataFolder().toPath()));
|
||||
@@ -356,6 +363,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
notice -> notifyPlayer(generation, notice), diagnostics, presentation, adventureSettings::enabled, gameModes);
|
||||
sessions.attachSwitchDelay(switchDelaySettings::delay);
|
||||
sessions.attachRoleplayDisabled(roleplaySettings::disabled);
|
||||
downedController=new games.dmg.fantasystick.session.DownedController(this,sessions,downed,Clock.systemUTC(),failure->getLogger().log(Level.WARNING,"Downed transition failed",failure));
|
||||
sessions.attachDowned(downed,downedSettings::timeout,downedController::open);
|
||||
combatFeedback = new games.dmg.fantasystick.presentation.CombatFeedback(feedbackPreferences, sessions);
|
||||
trainingDummyController = new games.dmg.fantasystick.training.TrainingDummyController(this, trainingDummies);
|
||||
parties = new games.dmg.fantasystick.party.PartyRoster(characterParties, sessions, partySettings::maximum);
|
||||
@@ -385,7 +394,9 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
Clock.systemUTC(), nextTick, id -> getServer().getPlayer(id),
|
||||
problem -> getLogger().log(Level.WARNING, "Combat reward failed for character " + problem.character(), problem.cause()),
|
||||
particleDelivery);
|
||||
sessions.attachPvpDefeat(combatExperience::consumePvpDefeat);
|
||||
sessions.attachDefeatCapture(combatExperience::captureDownedDefeat);
|
||||
sessions.attachDownedRewardAllocation(combatExperience::allocateDownedDefeat);
|
||||
sessions.attachDownedDefeatRewards(combatExperience::settleDownedDefeat);
|
||||
abilityRegistry = new games.dmg.fantasystick.ability.AbilityRegistry();
|
||||
fireballSettings = new games.dmg.fantasystick.persistence.FireballSettings(
|
||||
getDataFolder().toPath(), fireballConfiguration);
|
||||
@@ -465,6 +476,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
revive = new games.dmg.fantasystick.ability.Revive(characters, revivals, Clock.systemUTC(), nextTick,
|
||||
(size, title) -> getServer().createInventory(null, size, title),
|
||||
problem -> getLogger().log(Level.WARNING, "Revive transition failed", problem));
|
||||
revive.attachDowned(downedController,downedSettings::protection);
|
||||
abilityRegistry.register(fireball.definition());
|
||||
abilityRegistry.register(frostShard.definition());
|
||||
abilityRegistry.register(longbow.definition());
|
||||
@@ -581,7 +593,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
rareMerchantController=new games.dmg.fantasystick.shop.RareMerchantController(this,rareMerchants,rareShopMenus::open);
|
||||
rarePotions=new games.dmg.fantasystick.shop.RarePotionService(rareInventory,rareSettings,characters,sessions,event->getServer().getPluginManager().callEvent(event),nextTick,failure->getLogger().log(Level.WARNING,"Rare potion use failed",failure));
|
||||
rareReskills=new games.dmg.fantasystick.shop.RareReskillService(rareInventory,characters,sessions,nextTick,record->{for(String ability:record.learned())abilityEngine.remove(record.id(),ability);speedI.sweep();lowLightVision.sweep();},failure->getLogger().log(Level.WARNING,"Rare Reskill use failed",failure));
|
||||
rarePotions.install();rareReskills.install();books.attachRareInventory(rareInventory,rarePotions,rareReskills);
|
||||
rareMagicCores=new games.dmg.fantasystick.shop.RareMagicCoreService(rareInventory,characters,sessions,nextTick,failure->getLogger().log(Level.WARNING,"Rare Magic Core use failed",failure));
|
||||
rarePotions.install();rareReskills.install();rareMagicCores.install();books.attachRareInventory(rareInventory,rarePotions,rareReskills,rareMagicCores);
|
||||
adventureQuestController = new games.dmg.fantasystick.adventure.AdventureQuestController(this,
|
||||
adventureQuests, adventureQuestSettings, sessions, parties, characters, rules, nextTick,
|
||||
Clock.systemUTC(), java.util.random.RandomGenerator.getDefault(), particleDelivery);
|
||||
@@ -596,10 +609,11 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var bossRecoverySettings=outOfCombatRecoverySettings;var bossQuickerRegeneration=quickerRegeneration;var bossQuickerRegenerationII=quickerRegenerationII;var bossHealthStealSettings=healthStealSettings;
|
||||
dungeonController = new games.dmg.fantasystick.dungeon.DungeonController(this,dungeons,adventureQuests,sessions,parties,characters,rules,nextTick,java.util.random.RandomGenerator.getDefault(),abilityRegistry,passiveRegistry,bossRecoverySettings::settings,record->{if(!record.passives().contains(games.dmg.fantasystick.passive.QuickerRegenerationI.ID))return java.math.BigInteger.ZERO;var bonus=bossQuickerRegeneration.bonus();return record.passives().contains(games.dmg.fantasystick.passive.QuickerRegenerationII.ID)?bonus.add(bossQuickerRegenerationII.bonus()):bonus;},()->bossHealthStealSettings.settings().healing(),particleDelivery);
|
||||
dungeonController.registerFishing(fishingController);
|
||||
var custodyDirectory=dungeons;
|
||||
sessions.attachUnavailableCharacter(character->custodyDirectory.custody(character).isPresent());
|
||||
characters.attachUnavailableCharacter(character->custodyDirectory.custody(character).isPresent());
|
||||
characterParties.attachUnavailableCharacter(character->custodyDirectory.custody(character).isPresent());
|
||||
var custodyDirectory=dungeons;var downedDirectory=downed;
|
||||
java.util.function.Predicate<java.util.UUID> unavailableCharacter=character->custodyDirectory.custody(character).isPresent()||downedDirectory.all().stream().anyMatch(value->value.character().equals(character)&&value.phase()==games.dmg.fantasystick.session.DownedEpisode.Phase.PENDING);
|
||||
sessions.attachUnavailableCharacter(unavailableCharacter);
|
||||
characters.attachUnavailableCharacter(unavailableCharacter);
|
||||
characterParties.attachUnavailableCharacter(unavailableCharacter);
|
||||
dungeonCommands = new games.dmg.fantasystick.dungeon.DungeonCommands(this,dungeons,dungeonController,adventureQuests,nextTick,characters::find,character->sessions.activeCharacter(character).isPresent(),character->characterParties.partyOf(character).isPresent());
|
||||
adventureQuests.registerDungeonRewards(site->dungeons.find(site.id()).map(value->new games.dmg.fantasystick.adventure.AdventureQuestDirectory.Reward(value.maximumXp(),value.maximumCoins())).orElse(new games.dmg.fantasystick.adventure.AdventureQuestDirectory.Reward(java.math.BigInteger.ZERO,java.math.BigInteger.ZERO)));
|
||||
adventureQuests.registerDungeonSites(()->dungeons.snapshot().dungeons().stream().filter(value->dungeons.eligibleForFutureOffer(value.id())).map(value->new games.dmg.fantasystick.adventure.AdventureQuestState.Site(value.id(),games.dmg.fantasystick.adventure.AdventureQuestState.SiteType.DUNGEON,value.name(),value.world(),value.entrance().x(),value.entrance().y(),value.entrance().z(),null,value.participationMode())).toList());
|
||||
@@ -643,6 +657,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
admin.attachArmorers(armorers,armorerController);
|
||||
admin.attachArmorMarket(armorMarket);
|
||||
admin.attachRareMarket(rareMerchants,rareMerchantController,rareMarket,rareSettings);
|
||||
admin.attachDownedSettings(downedSettings);
|
||||
admin.attachCoinSettings(coinSettings);
|
||||
admin.attachHardMobXpSettings(hardMobXpSettings, combatExperience);
|
||||
admin.attachAdventureQuests(adventureQuestCommands, adventureQuestSettings);
|
||||
@@ -677,6 +692,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
getServer().getPluginManager().registerEvents(guard, this);
|
||||
getServer().getPluginManager().registerEvents(anvilNames, this);
|
||||
getServer().getPluginManager().registerEvents(sessionEvents, this);
|
||||
getServer().getPluginManager().registerEvents(downedController, this);
|
||||
getServer().getPluginManager().registerEvents(characterRecovery, this);
|
||||
getServer().getPluginManager().registerEvents(chatNames, this);
|
||||
getServer().getPluginManager().registerEvents(partyEvents, this);
|
||||
@@ -691,6 +707,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
getServer().getPluginManager().registerEvents(adventureQuestController,this);
|
||||
getServer().getPluginManager().registerEvents(fishingController,this);
|
||||
getServer().getPluginManager().registerEvents(dungeonController,this);
|
||||
downedController.install();
|
||||
partyRegistrarController.install();
|
||||
trainingDummyController.install();
|
||||
armorerController.install();
|
||||
@@ -782,16 +799,16 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
var closingAdventureQuestController = adventureQuestController; adventureQuestController = null;
|
||||
adventureQuestCommands = null;
|
||||
var closingFishing=fishing;fishing=null;var closingFishingController=fishingController;fishingController=null;
|
||||
var closingDungeons=dungeons;dungeons=null;var closingDungeonController=dungeonController;dungeonController=null;dungeonCommands=null;
|
||||
var closingDungeons=dungeons;dungeons=null;var closingDowned=downed;downed=null;var closingDownedController=downedController;downedController=null;var closingDungeonController=dungeonController;dungeonController=null;dungeonCommands=null;
|
||||
var closingPartyRegistrarMenus = partyRegistrarMenus; partyRegistrarMenus = null;
|
||||
var closingPartyManagement = partyManagement; partyManagement = null;
|
||||
var closingArmorers=armorers;armorers=null;var closingArmorerController=armorerController;armorerController=null;
|
||||
var closingArmorShopMenus=armorShopMenus;armorShopMenus=null;armorShop=null;
|
||||
var closingArmorMarket=armorMarket;armorMarket=null;var closingArmorMarketPulse=armorMarketPulse;armorMarketPulse=null;
|
||||
var closingArmorMenuPulse=armorMenuPulse;armorMenuPulse=null;
|
||||
var closingRareSettings=rareSettings;rareSettings=null;var closingRareInventory=rareInventory;rareInventory=null;
|
||||
var closingRareSettings=rareSettings;rareSettings=null;var closingDownedSettings=downedSettings;downedSettings=null;var closingRareInventory=rareInventory;rareInventory=null;
|
||||
var closingRareMerchants=rareMerchants;rareMerchants=null;var closingRareMerchantController=rareMerchantController;rareMerchantController=null;
|
||||
var closingRareMarket=rareMarket;rareMarket=null;var closingRareShopMenus=rareShopMenus;rareShopMenus=null;rareShop=null;rarePotions=null;rareReskills=null;
|
||||
var closingRareMarket=rareMarket;rareMarket=null;var closingRareShopMenus=rareShopMenus;rareShopMenus=null;rareShop=null;rarePotions=null;rareReskills=null;rareMagicCores=null;
|
||||
var closingRareMarketPulse=rareMarketPulse;rareMarketPulse=null;var closingRareMenuPulse=rareMenuPulse;rareMenuPulse=null;
|
||||
var closingCrafting = crafting; crafting = null;
|
||||
var closingGuard = guard; guard = null;
|
||||
@@ -915,6 +932,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
if (closingPartyEconomySettings != null) cleanup("party economy configuration", closingPartyEconomySettings::close);
|
||||
if(closingGearSettings!=null)cleanup("gear configuration",closingGearSettings::close);
|
||||
if(closingRareSettings!=null)cleanup("rare configuration",closingRareSettings::close);
|
||||
if(closingDownedSettings!=null)cleanup("downed configuration",closingDownedSettings::close);
|
||||
if (closingCoinSettings != null) cleanup("coin configuration", closingCoinSettings::close);
|
||||
if (closingHardMobXpSettings != null) cleanup("hard-mob XP configuration", closingHardMobXpSettings::close);
|
||||
if (closingAdventureQuestSettings != null) cleanup("adventure quest configuration", closingAdventureQuestSettings::close);
|
||||
@@ -924,6 +942,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
if(closingFishing!=null)cleanup("fishing persistence",closingFishing::close);
|
||||
if (closingDungeonController != null) cleanup("dungeons", closingDungeonController::close);
|
||||
if (closingDungeons != null) cleanup("dungeon persistence", closingDungeons::close);
|
||||
if (closingDownedController != null) cleanup("downed controller", closingDownedController::close);
|
||||
if (closingDowned != null) cleanup("downed persistence", closingDowned::close);
|
||||
if (closingSheetResourcePackSettings != null) cleanup("sheet resource-pack configuration", closingSheetResourcePackSettings::close);
|
||||
if (closingSheetResourcePack != null) cleanup("sheet resource-pack", closingSheetResourcePack::close);
|
||||
if (closingOutOfCombatRecoverySettings != null) cleanup("out-of-combat recovery configuration", closingOutOfCombatRecoverySettings::close);
|
||||
@@ -945,6 +965,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
closingArmorMarket==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingArmorMarket.drained().toCompletableFuture(),
|
||||
closingGearSettings==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingGearSettings.drained().toCompletableFuture(),
|
||||
closingRareSettings==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingRareSettings.drained().toCompletableFuture(),
|
||||
closingDownedSettings==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingDownedSettings.drained().toCompletableFuture(),
|
||||
closingRareInventory==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingRareInventory.drained().toCompletableFuture(),
|
||||
closingRareMerchants==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingRareMerchants.drained().toCompletableFuture(),
|
||||
closingRareMarket==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingRareMarket.drained().toCompletableFuture(),
|
||||
@@ -959,6 +980,8 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
closingFishing==null?java.util.concurrent.CompletableFuture.completedFuture(null):closingFishing.drained().toCompletableFuture(),
|
||||
closingDungeons == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingDungeons.drained().toCompletableFuture(),
|
||||
closingDowned == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingDowned.drained().toCompletableFuture(),
|
||||
closingSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
: closingSettings.drained().toCompletableFuture(),
|
||||
closingFireballSettings == null ? java.util.concurrent.CompletableFuture.completedFuture(null)
|
||||
@@ -1078,6 +1101,7 @@ public final class FantasyStickPlugin extends JavaPlugin {
|
||||
unregister(closingAdventureQuestController);
|
||||
unregister(closingFishingController);
|
||||
unregister(closingDungeonController);
|
||||
unregister(closingDownedController);
|
||||
unregister(closingCombatExperience);
|
||||
unregister(closingHealthSteal);
|
||||
unregister(closingFireball);
|
||||
|
||||
@@ -50,6 +50,8 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
private final Consumer<Throwable> failures;
|
||||
private final TailBooks tails = new TailBooks();
|
||||
private final CharacterSheets sheets = new CharacterSheets();
|
||||
private games.dmg.fantasystick.session.DownedController downed;
|
||||
private java.util.function.Supplier<Duration> downedProtection=()->Duration.ofSeconds(5);
|
||||
private final Map<Inventory, View> inventories = new IdentityHashMap<>();
|
||||
private final Map<UUID, View> targets = new LinkedHashMap<>();
|
||||
private boolean closed;
|
||||
@@ -80,6 +82,8 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
this.popups = Objects.requireNonNull(popups); this.failures = Objects.requireNonNull(failures);
|
||||
}
|
||||
|
||||
public void attachDowned(games.dmg.fantasystick.session.DownedController controller,java.util.function.Supplier<Duration> protection){if(closed||downed!=null)throw new IllegalStateException("Downed Revive already attached or closed");downed=Objects.requireNonNull(controller);downedProtection=Objects.requireNonNull(protection);}
|
||||
|
||||
public AbilityDefinition definition() {
|
||||
return new AbilityDefinition("revive", "Revive", Material.ECHO_SHARD,
|
||||
List.of("Let another player continue one fallen character.", "A valid cast spends the daily opportunity."),
|
||||
@@ -100,6 +104,7 @@ public final class Revive implements AbilityEffect, Listener, AutoCloseable {
|
||||
execution.input().player().sendMessage("Revive found no eligible player within 12 blocks and line of sight.");
|
||||
execution.finish(); return;
|
||||
}
|
||||
if(downed!=null&&downed.downed(target)){downed.revive(target,downedProtection.get(),status->{execution.input().player().sendMessage(switch(status){case APPLIED->"Revive restored the downed character in place.";case EXPIRED->"Revive arrived after the downed countdown expired.";case STALE->"That downed episode was already resolved or changed.";case FAILED->"Downed Revive is pending recovery; no second rescue was attempted.";});execution.finish();});return;}
|
||||
var captured = candidates(target);
|
||||
if (captured.isEmpty()) {
|
||||
execution.input().player().sendMessage("That player has no direct-inventory Tail eligible for Revive.");
|
||||
|
||||
@@ -33,6 +33,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
private games.dmg.fantasystick.shop.RareInventoryDirectory rareInventory;
|
||||
private games.dmg.fantasystick.shop.RarePotionService rarePotions;
|
||||
private games.dmg.fantasystick.shop.RareReskillService rareReskills;
|
||||
private games.dmg.fantasystick.shop.RareMagicCoreService rareMagicCores;
|
||||
private final org.bukkit.Server server;
|
||||
private final Map<UUID, Object> pending = new ConcurrentHashMap<>();
|
||||
private final Map<UUID, Object> adminPending = new ConcurrentHashMap<>();
|
||||
@@ -114,7 +115,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
}
|
||||
|
||||
public void attachFishingInventory(games.dmg.fantasystick.adventure.FishingDirectory fishing){if(closed||this.fishing!=null)throw new IllegalStateException("Fishing inventory already attached or books closed");this.fishing=Objects.requireNonNull(fishing);}
|
||||
public void attachRareInventory(games.dmg.fantasystick.shop.RareInventoryDirectory inventory,games.dmg.fantasystick.shop.RarePotionService potions,games.dmg.fantasystick.shop.RareReskillService reskills){if(closed||rareInventory!=null)throw new IllegalStateException("Rare inventory already attached or books closed");rareInventory=Objects.requireNonNull(inventory);rarePotions=Objects.requireNonNull(potions);rareReskills=Objects.requireNonNull(reskills);}
|
||||
public void attachRareInventory(games.dmg.fantasystick.shop.RareInventoryDirectory inventory,games.dmg.fantasystick.shop.RarePotionService potions,games.dmg.fantasystick.shop.RareReskillService reskills,games.dmg.fantasystick.shop.RareMagicCoreService magicCores){if(closed||rareInventory!=null)throw new IllegalStateException("Rare inventory already attached or books closed");rareInventory=Objects.requireNonNull(inventory);rarePotions=Objects.requireNonNull(potions);rareReskills=Objects.requireNonNull(reskills);rareMagicCores=Objects.requireNonNull(magicCores);}
|
||||
|
||||
@Override public void accept(ControlInput input) { load(input, 0); }
|
||||
|
||||
@@ -911,7 +912,7 @@ public final class CharacterBookController implements Consumer<ControlInput>, Au
|
||||
}
|
||||
|
||||
@org.bukkit.event.EventHandler
|
||||
public void rareAction(io.papermc.paper.event.player.PlayerCustomClickEvent event){if(closed||rarePotions==null||rareReskills==null||!RARE_USE.equals(event.getIdentifier())||!(event.getCommonConnection() instanceof io.papermc.paper.connection.PlayerGameConnection connection)||event.getTag()==null)return;var player=connection.getPlayer();var view=rareViews.get(player.getUniqueId());if(view==null||view.input().player()!=player)return;String raw=event.getTag().string();if(raw.length()>120)return;var match=RARE_PAYLOAD.matcher(raw);var product=match.matches()?games.dmg.fantasystick.shop.RareProduct.find(match.group(2)).orElse(null):null;if(product==null||!view.nonce().equals(match.group(1))||!view.quantities().getOrDefault(product.id(),java.math.BigInteger.ZERO).equals(rareInventory.quantity(view.input().session().character(),product))||!rareViews.remove(player.getUniqueId(),view)||!view.input().stillCurrent())return;if(product==games.dmg.fantasystick.shop.RareProduct.RESKILL){var preview=rareReskills.preview(player);if(preview.isEmpty()){player.sendMessage("Reskill preview refused: the character, session or quantity changed.");return;}if(preview.orElseThrow().refund().signum()==0){player.sendMessage("Reskill use refused: this character has no investments to reset.");load(view.input(),0);return;}var confirmation=new ReskillView(UUID.randomUUID().toString(),view.input(),preview.orElseThrow());reskillViews.put(player.getUniqueId(),confirmation);player.openBook(reskillConfirmation(confirmation));return;}if(!product.heals())return;rarePotions.use(player,product,outcome->{if(closed||!view.input().stillCurrent())return;player.sendMessage(switch(outcome.status()){case APPLIED->"Used "+product.displayName()+" and restored "+outcome.healed().toPlainString()+" health.";case FULL_HEALTH->"Potion use refused: health is already full.";case NO_EFFECT->"Potion use refused: no positive healing was accepted.";case NOT_AVAILABLE->"Potion use refused: that item is no longer available.";case STALE->"Potion use refused: the character, session or quantity changed.";case FAILED->"Potion use could not be acknowledged; retained proof prevents replay.";});load(view.input(),0);});}
|
||||
public void rareAction(io.papermc.paper.event.player.PlayerCustomClickEvent event){if(closed||rarePotions==null||rareReskills==null||rareMagicCores==null||!RARE_USE.equals(event.getIdentifier())||!(event.getCommonConnection() instanceof io.papermc.paper.connection.PlayerGameConnection connection)||event.getTag()==null)return;var player=connection.getPlayer();var view=rareViews.get(player.getUniqueId());if(view==null||view.input().player()!=player)return;String raw=event.getTag().string();if(raw.length()>120)return;var match=RARE_PAYLOAD.matcher(raw);var product=match.matches()?games.dmg.fantasystick.shop.RareProduct.find(match.group(2)).orElse(null):null;if(product==null||!view.nonce().equals(match.group(1))||!view.quantities().getOrDefault(product.id(),java.math.BigInteger.ZERO).equals(rareInventory.quantity(view.input().session().character(),product))||!rareViews.remove(player.getUniqueId(),view)||!view.input().stillCurrent())return;if(product==games.dmg.fantasystick.shop.RareProduct.RESKILL){var preview=rareReskills.preview(player);if(preview.isEmpty()){player.sendMessage("Reskill preview refused: the character, session or quantity changed.");return;}if(preview.orElseThrow().refund().signum()==0){player.sendMessage("Reskill use refused: this character has no investments to reset.");load(view.input(),0);return;}var confirmation=new ReskillView(UUID.randomUUID().toString(),view.input(),preview.orElseThrow());reskillViews.put(player.getUniqueId(),confirmation);player.openBook(reskillConfirmation(confirmation));return;}if(product==games.dmg.fantasystick.shop.RareProduct.MAGIC_CORE){rareMagicCores.use(player,outcome->{if(closed)return;player.sendMessage(switch(outcome.status()){case APPLIED->"Used Magic Core and gained 1 ordinary unspent point.";case NOT_AVAILABLE->"Magic Core use refused: that item is no longer available.";case STALE->"Magic Core use refused: the character, session, points or quantity changed.";case FAILED->"Magic Core could not be acknowledged; retained proof prevents replay.";});if(view.input().stillCurrent())load(view.input(),0);});return;}if(!product.heals())return;rarePotions.use(player,product,outcome->{if(closed||!view.input().stillCurrent())return;player.sendMessage(switch(outcome.status()){case APPLIED->"Used "+product.displayName()+" and restored "+outcome.healed().toPlainString()+" health.";case FULL_HEALTH->"Potion use refused: health is already full.";case NO_EFFECT->"Potion use refused: no positive healing was accepted.";case NOT_AVAILABLE->"Potion use refused: that item is no longer available.";case STALE->"Potion use refused: the character, session or quantity changed.";case FAILED->"Potion use could not be acknowledged; retained proof prevents replay.";});load(view.input(),0);});}
|
||||
|
||||
private static ItemStack reskillConfirmation(ReskillView view){var item=new ItemStack(Material.WRITTEN_BOOK);var meta=(BookMeta)item.getItemMeta();meta.setTitle("Confirm Reskill");meta.setAuthor("Fantasy Stick");var page=Component.text("Confirm Reskill\n\nRefund: "+view.preview().refund()+" points\nStats → 0\nAbilities/passives removed\nHealth only clamps to the new maximum\nCooldowns retained\n\n").append(Component.text("[Confirm Reskill]",net.kyori.adventure.text.format.NamedTextColor.DARK_RED).clickEvent(net.kyori.adventure.text.event.ClickEvent.custom(RARE_RESKILL_CONFIRM,net.kyori.adventure.nbt.api.BinaryTagHolder.binaryTagHolder("\""+view.nonce()+"\""))));meta.pages(java.util.List.of(page));item.setItemMeta(meta);return item;}
|
||||
|
||||
|
||||
@@ -12,12 +12,14 @@ import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import org.bukkit.Color;
|
||||
@@ -193,8 +195,25 @@ public final class CombatExperience implements Listener, AutoCloseable {
|
||||
defeat.level(), defeat.active().character(), defeat.coins());
|
||||
}
|
||||
|
||||
/** Consumed synchronously by the fantasy defeat transition before it persists the Tail state. */
|
||||
public boolean consumePvpDefeat(UUID player) { return pvpDefeats.remove(player); }
|
||||
/** Captures short-lived contributors before the downed wait; no reward is published yet. */
|
||||
public EquipmentSessions.DefeatCapture captureDownedDefeat(UUID player){
|
||||
var entry=defeats.entrySet().stream().filter(value->value.getValue().active().player().equals(player)).findFirst().orElse(null);
|
||||
if(entry==null)return new EquipmentSessions.DefeatCapture(pvpDefeats.remove(player),List.of(),0,BigInteger.ZERO);
|
||||
defeats.remove(entry.getKey());var defeat=entry.getValue();var direct=new ArrayList<>(contributions.consumeDirect(player,clock.instant()));direct.remove(defeat.active().character());boolean pvp=pvpDefeats.remove(player)||!direct.isEmpty();return new EquipmentSessions.DefeatCapture(pvp,List.copyOf(direct),defeat.level(),defeat.coins());
|
||||
}
|
||||
|
||||
/** Backward-compatible test adapter; production captures the complete durable context. */
|
||||
public boolean consumePvpDefeat(UUID player){return captureDownedDefeat(player).playerDefeat();}
|
||||
|
||||
/** Freeze final-time eligibility and exact shares before the durable death claim. */
|
||||
public List<games.dmg.fantasystick.session.DownedEpisode.Reward> allocateDownedDefeat(games.dmg.fantasystick.session.DownedEpisode episode){
|
||||
var attribution=episode.attribution();if(!attribution.playerDefeat()||attribution.contributors().isEmpty())return List.of();var units=rewardUnits(new ArrayList<>(attribution.contributors()));if(units.isEmpty())return List.of();var capturedRewards=rewards;var replaySafeRandom=new java.util.Random(episode.id().getMostSignificantBits()^episode.id().getLeastSignificantBits());var xp=games.dmg.fantasystick.progression.RewardAllocator.allocate(capturedRewards.pool(CombatRewardRules.Target.FANTASY_CHARACTER,attribution.victimLevel()),units,replaySafeRandom);var coins=games.dmg.fantasystick.progression.RewardAllocator.allocate(attribution.victimCoins(),units,replaySafeRandom);return xp.keySet().stream().sorted().map(character->new games.dmg.fantasystick.session.DownedEpisode.Reward(character,xp.get(character),coins.get(character))).toList();
|
||||
}
|
||||
|
||||
/** Apply only the shares frozen in the winning durable final-death claim. */
|
||||
public CompletionStage<Void> settleDownedDefeat(games.dmg.fantasystick.session.DownedEpisode episode){
|
||||
if(episode.finalRewards().isEmpty())return CompletableFuture.completedStage(null);var capturedRewards=rewards;var settlements=new ArrayList<CompletableFuture<Void>>();for(var reward:episode.finalRewards()){UUID receipt=UUID.nameUUIDFromBytes(("downed:"+episode.id()+":"+reward.character()).getBytes(java.nio.charset.StandardCharsets.UTF_8));var proposed=new PendingAward(receipt,reward.character(),reward.experience(),reward.coins(),null,capturedRewards);var existing=pending.putIfAbsent(receipt,proposed);var operation=existing==null?proposed:existing;settlements.add(operation.settled);attempt(operation);}return CompletableFuture.allOf(settlements.toArray(CompletableFuture[]::new));
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void mobDeath(EntityDeathEvent event) {
|
||||
|
||||
@@ -472,6 +472,11 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
/** One character-file transaction owns a rare purchase's exact idempotent coin debit. */
|
||||
public CompletableFuture<RarePurchase> purchaseRare(UUID characterId,BigInteger expectedRevision,UUID operationId,BigInteger price){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);Objects.requireNonNull(price);if(price.signum()<=0)throw new IllegalArgumentException("Invalid rare purchase");return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new RarePurchase(RarePurchaseStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new RarePurchase(RarePurchaseStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new RarePurchase(RarePurchaseStatus.STALE,Optional.of(old));if(old.coins().compareTo(price)<0)return new RarePurchase(RarePurchaseStatus.INSUFFICIENT,Optional.of(old));var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);var saved=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),old.stats(),old.level(),old.experience(),old.unspentPoints(),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,old.deathId(),old.diedAt(),old.coins().subtract(price),true,receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new RarePurchase(RarePurchaseStatus.APPLIED,Optional.of(saved));});}
|
||||
|
||||
public enum MagicCoreStatus { APPLIED,DUPLICATE,STALE,UNAVAILABLE }
|
||||
public record MagicCore(MagicCoreStatus status,Optional<CharacterRecord> record){}
|
||||
/** Credit one ordinary arbitrary-precision point with stable consume proof. */
|
||||
public CompletableFuture<MagicCore> consumeMagicCore(UUID characterId,BigInteger expectedRevision,UUID operationId){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(operationId);return submit(()->{var found=repository.load(characterId);if(found.isEmpty()||found.orElseThrow().dead())return new MagicCore(MagicCoreStatus.UNAVAILABLE,Optional.empty());var old=found.orElseThrow();if(old.rewardReceipts().contains(operationId))return new MagicCore(MagicCoreStatus.DUPLICATE,Optional.of(old));if(!old.revision().equals(expectedRevision))return new MagicCore(MagicCoreStatus.STALE,Optional.of(old));var receipts=new java.util.HashSet<>(old.rewardReceipts());if(receipts.size()>=4096)receipts.remove(receipts.stream().min(UUID::compareTo).orElseThrow());receipts.add(operationId);var saved=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),old.stats(),old.level(),old.experience(),old.unspentPoints().add(BigInteger.ONE),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,old.deathId(),old.diedAt(),old.coins(),old.coinsInitialized(),receipts,old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(saved,old.revision());return new MagicCore(MagicCoreStatus.APPLIED,Optional.of(saved));});}
|
||||
|
||||
public enum ReskillStatus { APPLIED,DUPLICATE,NOTHING_TO_RESET,STALE,UNAVAILABLE }
|
||||
public record Reskill(ReskillStatus status,Optional<CharacterRecord> record){}
|
||||
/** Reset every one-point character investment and preserve identity/progress/deadlines in one revision. */
|
||||
@@ -795,6 +800,9 @@ public final class CharacterStorage implements AutoCloseable {
|
||||
return death(characterId, null, loseCoins);
|
||||
}
|
||||
|
||||
/** Finalize one claimed downed outcome with its stable death identity and original resolution time. */
|
||||
public CompletableFuture<Optional<CharacterRecord>> recordFinalDeath(UUID characterId,BigInteger expectedRevision,UUID deathId,Instant diedAt,boolean loseCoins){Objects.requireNonNull(characterId);Objects.requireNonNull(expectedRevision);Objects.requireNonNull(deathId);Objects.requireNonNull(diedAt);return submit(()->{var found=repository.load(characterId);if(found.isEmpty())return Optional.empty();var old=found.orElseThrow();if(old.dead())return old.deathId().equals(deathId)&&old.diedAt().equals(diedAt)?Optional.of(old):Optional.empty();if(!old.revision().equals(expectedRevision))return Optional.empty();var dead=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),old.stats(),old.level(),old.experience(),old.unspentPoints(),java.math.BigDecimal.ZERO,old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),true,deathId,diedAt,loseCoins?BigInteger.ZERO:old.coins(),old.coinsInitialized(),old.rewardReceipts(),loseCoins?old.coins():BigInteger.ZERO,old.gear(),old.sheetGeneration());repository.replace(dead,old.revision());return Optional.of(dead);});}
|
||||
|
||||
private CompletableFuture<Optional<CharacterRecord>> death(UUID characterId, BigInteger expectedRevision, boolean loseCoins) {
|
||||
Objects.requireNonNull(characterId);
|
||||
Instant diedAt = clock.instant();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/** Save-before-publication downed countdown and Revive protection policy. */
|
||||
public final class DownedSettings implements AutoCloseable{
|
||||
public static final String TIMEOUT="downed-timeout-seconds",PROTECTION="revive-downed-invulnerability-seconds";private static final Map<String,String> DEFAULTS=Map.of(TIMEOUT,"300",PROTECTION,"5");
|
||||
public record Update(String key,String value,Map<String,String> values,long sequence){public Update{values=Map.copyOf(values);}}
|
||||
private final Path directory;private final ExecutorService worker=Executors.newSingleThreadExecutor(task->new Thread(task,"fantasy-downed-configuration"));private volatile Map<String,String> effective;private Map<String,String> persisted;private long saved,published;private boolean closed;private int pending;private final CompletableFuture<Void> drained=new CompletableFuture<>();
|
||||
public DownedSettings(Path directory,Map<String,String> initial){this.directory=directory.toAbsolutePath();var values=new LinkedHashMap<String,String>();for(String key:keys())values.put(key,initial.getOrDefault(key,DEFAULTS.get(key)));validate(values);effective=Map.copyOf(values);persisted=effective;}
|
||||
public static List<String> keys(){return List.of(TIMEOUT,PROTECTION);}public static String defaultValue(String key){return DEFAULTS.get(key);}public String value(String key){return effective.get(key);}public Duration timeout(){return Duration.ofSeconds(Long.parseLong(effective.get(TIMEOUT)));}public Duration protection(){return Duration.ofSeconds(Long.parseLong(effective.get(PROTECTION)));}
|
||||
public CompletionStage<Update> set(String key,String raw){if(!DEFAULTS.containsKey(key))throw new IllegalArgumentException("Unknown downed setting");String value=Long.toString(seconds(raw,key.equals(TIMEOUT)));var preview=new LinkedHashMap<>(effective);preview.put(key,value);validate(preview);synchronized(this){if(closed)return CompletableFuture.failedStage(new IOException("Configuration closed"));pending++;}return CompletableFuture.supplyAsync(()->{try{var next=new LinkedHashMap<>(persisted);next.put(key,value);save(key,value);persisted=Map.copyOf(next);return new Update(key,value,persisted,++saved);}catch(IOException failure){throw new CompletionException(failure);}finally{finished();}},worker).minimalCompletionStage();}
|
||||
public synchronized boolean publish(Update update){if(update.sequence()<=published)return false;validate(update.values());effective=update.values();published=update.sequence();return true;}
|
||||
private static void validate(Map<String,String> values){seconds(values.get(TIMEOUT),true);seconds(values.get(PROTECTION),false);}private static long seconds(String raw,boolean positive){var value=new java.math.BigDecimal(Objects.requireNonNull(raw));long seconds=value.longValueExact();if(seconds<(positive?1:0)||seconds>Duration.ofDays(365).toSeconds())throw new IllegalArgumentException("Invalid duration");return seconds;}
|
||||
private void save(String key,String value)throws IOException{Files.createDirectories(directory);Path file=directory.resolve("config.yml"),lockFile=directory.resolve(".config.lock");try(var channel=FileChannel.open(lockFile,StandardOpenOption.CREATE,StandardOpenOption.WRITE,LinkOption.NOFOLLOW_LINKS);var lock=channel.tryLock()){if(lock==null)throw new IOException("Configuration busy");Map<String,Object> document=new LinkedHashMap<>();if(Files.exists(file,LinkOption.NOFOLLOW_LINKS)){if(!Files.isRegularFile(file,LinkOption.NOFOLLOW_LINKS)||Files.isSymbolicLink(file)||Files.size(file)>1_048_576)throw new IOException("Unsafe configuration");Object loaded=yaml().load(Files.readString(file,StandardCharsets.UTF_8));if(loaded instanceof Map<?,?> map)for(var entry:map.entrySet()){if(!(entry.getKey() instanceof String name))throw new IOException("Invalid key");document.put(name,entry.getValue());}}document.put(key,Long.parseLong(value));Path temporary=Files.createTempFile(directory,".config-downed-",".tmp");try{byte[] bytes=yaml().dump(document).getBytes(StandardCharsets.UTF_8);try(var output=FileChannel.open(temporary,StandardOpenOption.WRITE)){var buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())output.write(buffer);output.force(true);}Files.move(temporary,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);try(var parent=FileChannel.open(directory,StandardOpenOption.READ)){parent.force(true);}}finally{Files.deleteIfExists(temporary);}}catch(OverlappingFileLockException busy){throw new IOException("Configuration busy",busy);}}
|
||||
private static Yaml yaml(){var options=new LoaderOptions();options.setAllowDuplicateKeys(false);options.setMaxAliasesForCollections(20);options.setCodePointLimit(1_048_576);return new Yaml(new SafeConstructor(options));}private synchronized void finished(){pending--;if(closed&&pending==0)drained.complete(null);}public CompletionStage<Void> drained(){return drained.minimalCompletionStage();}@Override public synchronized void close(){closed=true;worker.shutdown();if(pending==0)drained.complete(null);}
|
||||
}
|
||||
@@ -146,6 +146,9 @@ public final class EquipmentSessionStore implements AutoCloseable {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Reopen only the exact completed session retained by durable downed custody. */
|
||||
public CompletionStage<State> resume(UUID player,UUID session,UUID character,String previousGameMode,OrdinaryVitals ordinaryVitals){Objects.requireNonNull(player);Objects.requireNonNull(session);Objects.requireNonNull(character);var receipt=new Receipt(session,character,clock.instant(),previousGameMode,ordinaryVitals);return submit(()->withLock(()->{var old=load(player).orElseThrow(()->new IOException("Completed equipment session not found"));if(old.pending()!=null||old.lastExit()==null||!session.equals(old.lastExit().sessionId())||!character.equals(old.lastExit().characterId()))throw new IOException("Completed equipment session does not match downed custody");return write(new State(player,old.revision().add(BigInteger.ONE),receipt,old.lastExit()));}));}
|
||||
|
||||
/** Capture the actual exit request time, never queue completion time. The receipt remains pending. */
|
||||
public CompletionStage<State> recordExit(UUID player, UUID session, Duration delay) {
|
||||
Objects.requireNonNull(player);
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
import org.bukkit.event.EventPriority;
|
||||
import org.bukkit.event.Listener;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/** Native freeze, bounded death decision menu and timeout publication for durable episodes. */
|
||||
public final class DownedController implements Listener,AutoCloseable{
|
||||
public enum RescueStatus{APPLIED,STALE,EXPIRED,FAILED}
|
||||
private record Holder(UUID episode)implements InventoryHolder{public Inventory getInventory(){return null;}}
|
||||
private final Plugin plugin;private final EquipmentSessions sessions;private final DownedDirectory directory;private final Clock clock;private final Consumer<Throwable> failures;private final java.util.Map<UUID,Boolean> gravity=new java.util.HashMap<>();private final java.util.Set<UUID> revertingSlots=new java.util.HashSet<>();private org.bukkit.scheduler.BukkitTask pulse;private boolean closed;
|
||||
public DownedController(Plugin plugin,EquipmentSessions sessions,DownedDirectory directory,Clock clock,Consumer<Throwable> failures){this.plugin=Objects.requireNonNull(plugin);this.sessions=Objects.requireNonNull(sessions);this.directory=Objects.requireNonNull(directory);this.clock=Objects.requireNonNull(clock);this.failures=Objects.requireNonNull(failures);}
|
||||
public void install(){if(pulse!=null)throw new IllegalStateException("Downed controller already installed");pulse=plugin.getServer().getScheduler().runTaskTimer(plugin,this::pulse,20L,20L);for(var episode:directory.all()){if(episode.phase()==DownedEpisode.Phase.PENDING){if(clock.instant().isBefore(episode.expiresAt()))open(episode);else finalizeDeath(episode);}else if(episode.outcome()==DownedEpisode.Outcome.FINAL_DEATH&&!episode.published())sessions.finalizeDowned(episode);}}
|
||||
public void open(DownedEpisode episode){if(closed||episode.phase()!=DownedEpisode.Phase.PENDING)return;var player=plugin.getServer().getPlayer(episode.player());if(player==null||!player.isOnline())return;freeze(player);var inventory=plugin.getServer().createInventory(new Holder(episode.id()),27,Component.text("Downed — "+remaining(episode)+"s"));inventory.setItem(11,item(Material.SKELETON_SKULL,"Accept Death",true));inventory.setItem(13,item(Material.GRAY_DYE,"Use Phoenix Down — unavailable",false));inventory.setItem(15,item(Material.GRAY_DYE,"Wait for Revive",false));player.openInventory(inventory);}
|
||||
private static ItemStack item(Material material,String name,boolean action){var item=new ItemStack(material);var meta=item.getItemMeta();meta.displayName(Component.text(name));if(!action)meta.lore(java.util.List.of(Component.text("Waiting does not pause the countdown.")));item.setItemMeta(meta);return item;}
|
||||
private long remaining(DownedEpisode episode){var remaining=java.time.Duration.between(clock.instant(),episode.expiresAt());if(remaining.isNegative()||remaining.isZero())return 0;return remaining.getSeconds()+(remaining.getNano()==0?0:1);}
|
||||
private void pulse(){if(closed)return;for(var episode:directory.all()){if(episode.phase()!=DownedEpisode.Phase.PENDING)continue;if(!clock.instant().isBefore(episode.expiresAt()))finalizeDeath(episode);else{var player=plugin.getServer().getPlayer(episode.player());if(player!=null&&player.isOnline()){if(player.getOpenInventory().getTopInventory().getHolder() instanceof Holder holder&&holder.episode().equals(episode.id()))player.getOpenInventory().setTitle("Downed — "+remaining(episode)+"s");else open(episode);}}}}
|
||||
public boolean downed(Player player){return sessions.downed(player.getUniqueId()).isPresent();}
|
||||
private void freeze(Player player){gravity.putIfAbsent(player.getUniqueId(),player.hasGravity());player.setGravity(false);player.setFallDistance(0);player.setVelocity(new org.bukkit.util.Vector());if(player.isInsideVehicle())player.leaveVehicle();}
|
||||
private void release(Player player){var original=gravity.remove(player.getUniqueId());if(original!=null)player.setGravity(original);revertingSlots.remove(player.getUniqueId());}
|
||||
public void revive(Player target,Duration protection,Consumer<RescueStatus> result){var episode=sessions.downed(target.getUniqueId()).orElse(null);if(episode==null){result.accept(RescueStatus.STALE);return;}directory.claim(episode.id(),DownedEpisode.Outcome.REVIVED,UUID.randomUUID(),protection).whenComplete((claim,failure)->schedule(()->{if(failure!=null){report(failure);result.accept(RescueStatus.FAILED);return;}if(claim.status()==DownedDirectory.ClaimStatus.EXPIRED){result.accept(RescueStatus.EXPIRED);return;}if(claim.status()!=DownedDirectory.ClaimStatus.APPLIED){result.accept(RescueStatus.STALE);return;}var resolved=claim.episode().orElseThrow();sessions.reviveDowned(resolved,applied->{if(!applied){result.accept(RescueStatus.FAILED);return;}release(target);directory.publish(resolved.id(),resolved.outcomeOperation()).whenComplete((published,publishFailure)->schedule(()->{if(publishFailure!=null){report(publishFailure);result.accept(RescueStatus.FAILED);}else result.accept(RescueStatus.APPLIED);}));});}));}
|
||||
private void finalizeDeath(DownedEpisode episode){java.util.List<DownedEpisode.Reward> rewards;try{rewards=sessions.finalRewards(episode);}catch(RuntimeException failure){report(failure);return;}directory.claim(episode.id(),DownedEpisode.Outcome.FINAL_DEATH,UUID.randomUUID(),Duration.ZERO,rewards).whenComplete((claim,failure)->schedule(()->{if(failure!=null){report(failure);return;}if(claim.status()==DownedDirectory.ClaimStatus.APPLIED){var player=plugin.getServer().getPlayer(episode.player());if(player!=null)release(player);sessions.finalizeDowned(claim.episode().orElseThrow());}}));}
|
||||
@EventHandler(priority=EventPriority.HIGHEST)public void click(org.bukkit.event.inventory.InventoryClickEvent event){if(event.getWhoClicked() instanceof Player actor&&sessions.downed(actor.getUniqueId()).isPresent())event.setCancelled(true);if(!(event.getView().getTopInventory().getHolder() instanceof Holder holder))return;event.setCancelled(true);if(!(event.getWhoClicked() instanceof Player player)||event.getRawSlot()!=11)return;var episode=directory.all().stream().filter(value->value.id().equals(holder.episode())&&value.player().equals(player.getUniqueId())&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);if(episode!=null)finalizeDeath(episode);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST)public void drag(org.bukkit.event.inventory.InventoryDragEvent event){if(event.getWhoClicked() instanceof Player actor&&sessions.downed(actor.getUniqueId()).isPresent()||event.getView().getTopInventory().getHolder() instanceof Holder)event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.MONITOR)public void closeMenu(org.bukkit.event.inventory.InventoryCloseEvent event){if(!(event.getView().getTopInventory().getHolder() instanceof Holder holder)||closed)return;plugin.getServer().getScheduler().runTask(plugin,()->directory.all().stream().filter(value->value.id().equals(holder.episode())&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().ifPresent(this::open));}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void damage(org.bukkit.event.entity.EntityDamageEvent event){if(event.getEntity() instanceof Player player&&(sessions.downed(player.getUniqueId()).isPresent()||sessions.downedProtected(player.getUniqueId())))event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void heal(org.bukkit.event.entity.EntityRegainHealthEvent event){if(event.getEntity() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void move(org.bukkit.event.player.PlayerMoveEvent event){var episode=sessions.downed(event.getPlayer().getUniqueId()).orElse(null);if(episode==null||event.getTo()==null)return;if(event.getFrom().getX()!=event.getTo().getX()||event.getFrom().getY()!=event.getTo().getY()||event.getFrom().getZ()!=event.getTo().getZ())event.setTo(event.getFrom());}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void teleport(org.bukkit.event.player.PlayerTeleportEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent()&&!sessions.downedRelocation(event.getPlayer().getUniqueId()))event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void velocity(org.bukkit.event.player.PlayerVelocityEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void drop(org.bukkit.event.player.PlayerDropItemEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void swap(org.bukkit.event.player.PlayerSwapHandItemsEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void interact(org.bukkit.event.player.PlayerInteractEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void interactEntity(org.bukkit.event.player.PlayerInteractEntityEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void attack(org.bukkit.event.entity.EntityDamageByEntityEvent event){if(event.getDamager() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void consume(org.bukkit.event.player.PlayerItemConsumeEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void hunger(org.bukkit.event.entity.FoodLevelChangeEvent event){if(event.getEntity() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void effect(org.bukkit.event.entity.EntityPotionEffectEvent event){if(event.getEntity() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void vehicle(org.bukkit.event.vehicle.VehicleEnterEvent event){if(event.getEntered() instanceof Player player&&sessions.downed(player.getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.HIGHEST,ignoreCancelled=true)public void flight(org.bukkit.event.player.PlayerToggleFlightEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isPresent())event.setCancelled(true);}
|
||||
@EventHandler(priority=EventPriority.MONITOR)public void slot(io.papermc.paper.event.player.PlayerInventorySlotChangeEvent event){var player=event.getPlayer();if(sessions.downed(player.getUniqueId()).isEmpty()||!revertingSlots.add(player.getUniqueId()))return;var old=event.getOldItemStack()==null?null:event.getOldItemStack().clone();schedule(()->{try{if(sessions.downed(player.getUniqueId()).isPresent())player.getInventory().setItem(event.getSlot(),old);}finally{revertingSlots.remove(player.getUniqueId());}});}
|
||||
@EventHandler(priority=EventPriority.MONITOR)public void quit(org.bukkit.event.player.PlayerQuitEvent event){release(event.getPlayer());}
|
||||
private void schedule(Runnable action){try{plugin.getServer().getScheduler().runTask(plugin,action);}catch(RuntimeException failure){report(failure);}}private void report(Throwable failure){try{failures.accept(failure);}catch(RuntimeException ignored){}}
|
||||
@Override public void close(){closed=true;if(pulse!=null)pulse.cancel();pulse=null;for(UUID player:java.util.List.copyOf(gravity.keySet())){var online=plugin.getServer().getPlayer(player);if(online!=null)release(online);}gravity.clear();revertingSlots.clear();}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.time.*;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import org.yaml.snakeyaml.LoaderOptions;
|
||||
import org.yaml.snakeyaml.Yaml;
|
||||
import org.yaml.snakeyaml.constructor.SafeConstructor;
|
||||
|
||||
/** Serialized forced-atomic authority for durable downed episodes and their one outcome. */
|
||||
public final class DownedDirectory implements AutoCloseable{
|
||||
public enum ClaimStatus{APPLIED,EXPIRED,ALREADY_RESOLVED,NOT_FOUND}
|
||||
public record Claim(ClaimStatus status,Optional<DownedEpisode> episode){}
|
||||
private final Path file;private final Clock clock;private final ExecutorService worker=Executors.newSingleThreadExecutor(task->new Thread(task,"fantasy-downed-persistence"));private volatile Map<UUID,DownedEpisode> snapshot;private boolean closed;private int pending;private final CompletableFuture<Void> drained=new CompletableFuture<>();
|
||||
public DownedDirectory(Path data,Clock clock)throws IOException{file=data.toAbsolutePath().resolve("downed.yml");this.clock=Objects.requireNonNull(clock);snapshot=load();}
|
||||
public CompletableFuture<Optional<DownedEpisode>> find(UUID character){return submit(()->Optional.ofNullable(snapshot.get(character)));}
|
||||
public List<DownedEpisode> all(){return List.copyOf(snapshot.values());}
|
||||
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,Duration timeout,DownedEpisode.Attribution attribution){return begin(character,player,session,world,x,y,z,yaw,pitch,world,x,y,z,yaw,pitch,timeout,attribution);}
|
||||
public CompletableFuture<DownedEpisode> begin(UUID character,UUID player,UUID session,UUID world,double x,double y,double z,float yaw,float pitch,UUID entryWorld,double entryX,double entryY,double entryZ,float entryYaw,float entryPitch,Duration timeout,DownedEpisode.Attribution attribution){Objects.requireNonNull(timeout);if(timeout.isZero()||timeout.isNegative()||timeout.compareTo(Duration.ofDays(365))>0)throw new IllegalArgumentException("Invalid downed timeout");return submit(()->{var existing=snapshot.get(character);if(existing!=null&&existing.phase()==DownedEpisode.Phase.PENDING)return existing;if(snapshot.values().stream().anyMatch(value->value.player().equals(player)&&value.phase()==DownedEpisode.Phase.PENDING))throw new IOException("Player already has a downed episode");var now=clock.instant().truncatedTo(ChronoUnit.SECONDS);var value=new DownedEpisode(UUID.randomUUID(),character,player,session,world,x,y,z,yaw,pitch,entryWorld,entryX,entryY,entryZ,entryYaw,entryPitch,now,now.plus(timeout),attribution,DownedEpisode.Phase.PENDING,null,null,null,null,List.of(),false);var next=new LinkedHashMap<>(snapshot);next.put(character,value);save(next);return value;});}
|
||||
public CompletableFuture<Claim> claim(UUID episodeId,DownedEpisode.Outcome outcome,UUID operation,Duration protection){return claim(episodeId,outcome,operation,protection,List.of());}
|
||||
public CompletableFuture<Claim> claim(UUID episodeId,DownedEpisode.Outcome outcome,UUID operation,Duration protection,List<DownedEpisode.Reward> rewards){Objects.requireNonNull(episodeId);Objects.requireNonNull(outcome);Objects.requireNonNull(operation);Objects.requireNonNull(protection);rewards=List.copyOf(rewards);if(protection.isNegative()||protection.compareTo(Duration.ofDays(365))>0||outcome==DownedEpisode.Outcome.REVIVED&&!rewards.isEmpty())throw new IllegalArgumentException("Invalid protection or rewards");var capturedRewards=rewards;return submit(()->{var current=snapshot.values().stream().filter(value->value.id().equals(episodeId)).findFirst().orElse(null);if(current==null)return new Claim(ClaimStatus.NOT_FOUND,Optional.empty());if(current.phase()==DownedEpisode.Phase.RESOLVED)return new Claim(ClaimStatus.ALREADY_RESOLVED,Optional.of(current));var now=clock.instant().truncatedTo(ChronoUnit.SECONDS);if(outcome==DownedEpisode.Outcome.REVIVED&&!now.isBefore(current.expiresAt()))return new Claim(ClaimStatus.EXPIRED,Optional.of(current));var resolvedAt=outcome==DownedEpisode.Outcome.FINAL_DEATH&&!now.isBefore(current.expiresAt())?current.expiresAt():now;var protectionUntil=outcome==DownedEpisode.Outcome.REVIVED?resolvedAt.plus(protection):null;var resolved=new DownedEpisode(current.id(),current.character(),current.player(),current.session(),current.world(),current.x(),current.y(),current.z(),current.yaw(),current.pitch(),current.entryWorld(),current.entryX(),current.entryY(),current.entryZ(),current.entryYaw(),current.entryPitch(),current.downedAt(),current.expiresAt(),current.attribution(),DownedEpisode.Phase.RESOLVED,outcome,operation,resolvedAt,protectionUntil,capturedRewards,false);var next=new LinkedHashMap<>(snapshot);next.put(resolved.character(),resolved);save(next);return new Claim(ClaimStatus.APPLIED,Optional.of(resolved));});}
|
||||
public CompletableFuture<DownedEpisode> publish(UUID episodeId,UUID operation){Objects.requireNonNull(episodeId);Objects.requireNonNull(operation);return submit(()->{var current=snapshot.values().stream().filter(value->value.id().equals(episodeId)).findFirst().orElseThrow(()->new IOException("Downed episode not found"));if(current.phase()!=DownedEpisode.Phase.RESOLVED||!operation.equals(current.outcomeOperation()))throw new IOException("Downed outcome operation does not match");if(current.published())return current;var published=new DownedEpisode(current.id(),current.character(),current.player(),current.session(),current.world(),current.x(),current.y(),current.z(),current.yaw(),current.pitch(),current.entryWorld(),current.entryX(),current.entryY(),current.entryZ(),current.entryYaw(),current.entryPitch(),current.downedAt(),current.expiresAt(),current.attribution(),current.phase(),current.outcome(),current.outcomeOperation(),current.resolvedAt(),current.protectionUntil(),current.finalRewards(),true);var next=new LinkedHashMap<>(snapshot);next.put(published.character(),published);save(next);return published;});}
|
||||
|
||||
private Map<UUID,DownedEpisode> load()throws IOException{if(Files.notExists(file))return Map.of();try{if(!Files.isRegularFile(file,LinkOption.NOFOLLOW_LINKS)||Files.isSymbolicLink(file)||Files.size(file)>1_048_576)throw new IllegalArgumentException();Object decoded=yaml().load(Files.readString(file,StandardCharsets.UTF_8));if(!(decoded instanceof Map<?,?> root)||!"1".equals(String.valueOf(root.get("schema-version"))))throw new IllegalArgumentException();var result=new LinkedHashMap<UUID,DownedEpisode>();for(Object raw:list(root.get("episodes"))){var row=map(raw);var value=decode(row);if(result.put(value.character(),value)!=null)throw new IllegalArgumentException();}return Map.copyOf(result);}catch(RuntimeException invalid){throw new IOException("Invalid downed state",invalid);}}
|
||||
private void save(Map<UUID,DownedEpisode> state)throws IOException{Files.createDirectories(file.getParent());var root=new LinkedHashMap<String,Object>();root.put("schema-version","1");root.put("episodes",state.values().stream().sorted(Comparator.comparing(DownedEpisode::character)).map(this::encode).toList());Path temporary=Files.createTempFile(file.getParent(),".downed-",".tmp");try{byte[] bytes=yaml().dump(root).getBytes(StandardCharsets.UTF_8);try(var out=FileChannel.open(temporary,StandardOpenOption.WRITE)){var buffer=ByteBuffer.wrap(bytes);while(buffer.hasRemaining())out.write(buffer);out.force(true);}Files.move(temporary,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);try(var directory=FileChannel.open(file.getParent(),StandardOpenOption.READ)){directory.force(true);}snapshot=Map.copyOf(state);}finally{Files.deleteIfExists(temporary);}}
|
||||
private Map<String,Object> encode(DownedEpisode value){var row=new LinkedHashMap<String,Object>();row.put("id",value.id().toString());row.put("character",value.character().toString());row.put("player",value.player().toString());row.put("session",value.session().toString());row.put("world",value.world().toString());row.put("x",BigDecimal.valueOf(value.x()).toPlainString());row.put("y",BigDecimal.valueOf(value.y()).toPlainString());row.put("z",BigDecimal.valueOf(value.z()).toPlainString());row.put("yaw",Float.toString(value.yaw()));row.put("pitch",Float.toString(value.pitch()));row.put("entry-world",value.entryWorld().toString());row.put("entry-x",BigDecimal.valueOf(value.entryX()).toPlainString());row.put("entry-y",BigDecimal.valueOf(value.entryY()).toPlainString());row.put("entry-z",BigDecimal.valueOf(value.entryZ()).toPlainString());row.put("entry-yaw",Float.toString(value.entryYaw()));row.put("entry-pitch",Float.toString(value.entryPitch()));row.put("downed-at",value.downedAt().toString());row.put("expires-at",value.expiresAt().toString());row.put("attacker",value.attribution().attacker()==null?null:value.attribution().attacker().toString());row.put("cause",value.attribution().cause());row.put("player-defeat",value.attribution().playerDefeat());row.put("contributors",value.attribution().contributors().stream().map(UUID::toString).collect(java.util.stream.Collectors.toCollection(ArrayList::new)));row.put("victim-level",value.attribution().victimLevel());row.put("victim-coins",value.attribution().victimCoins().toString());row.put("phase",value.phase().name());row.put("outcome",value.outcome()==null?null:value.outcome().name());row.put("outcome-operation",value.outcomeOperation()==null?null:value.outcomeOperation().toString());row.put("resolved-at",value.resolvedAt()==null?null:value.resolvedAt().toString());row.put("protection-until",value.protectionUntil()==null?null:value.protectionUntil().toString());row.put("final-rewards",value.finalRewards().stream().map(reward->{var saved=new LinkedHashMap<String,Object>();saved.put("character",reward.character().toString());saved.put("experience",reward.experience().toString());saved.put("coins",reward.coins().toString());return saved;}).collect(java.util.stream.Collectors.toCollection(ArrayList::new)));row.put("published",value.published());return row;}
|
||||
private DownedEpisode decode(Map<?,?> row){String attacker=optional(row,"attacker"),outcome=optional(row,"outcome"),operation=optional(row,"outcome-operation"),resolved=optional(row,"resolved-at"),protection=optional(row,"protection-until");UUID world=uuid(row,"world"),entryWorld=row.containsKey("entry-world")?uuid(row,"entry-world"):world;double x=Double.parseDouble(text(row,"x")),y=Double.parseDouble(text(row,"y")),z=Double.parseDouble(text(row,"z"));float yaw=Float.parseFloat(text(row,"yaw")),pitch=Float.parseFloat(text(row,"pitch"));return new DownedEpisode(uuid(row,"id"),uuid(row,"character"),uuid(row,"player"),uuid(row,"session"),world,x,y,z,yaw,pitch,entryWorld,row.containsKey("entry-x")?Double.parseDouble(text(row,"entry-x")):x,row.containsKey("entry-y")?Double.parseDouble(text(row,"entry-y")):y,row.containsKey("entry-z")?Double.parseDouble(text(row,"entry-z")):z,row.containsKey("entry-yaw")?Float.parseFloat(text(row,"entry-yaw")):yaw,row.containsKey("entry-pitch")?Float.parseFloat(text(row,"entry-pitch")):pitch,Instant.parse(text(row,"downed-at")),Instant.parse(text(row,"expires-at")),new DownedEpisode.Attribution(attacker==null?null:UUID.fromString(attacker),text(row,"cause"),Boolean.parseBoolean(String.valueOf(row.containsKey("player-defeat")?row.get("player-defeat"):false)),row.containsKey("contributors")?list(row.get("contributors")).stream().map(String::valueOf).map(UUID::fromString).toList():List.of(),row.containsKey("victim-level")?Integer.parseInt(String.valueOf(row.get("victim-level"))):0,row.containsKey("victim-coins")?new java.math.BigInteger(String.valueOf(row.get("victim-coins"))):java.math.BigInteger.ZERO),DownedEpisode.Phase.valueOf(text(row,"phase")),outcome==null?null:DownedEpisode.Outcome.valueOf(outcome),operation==null?null:UUID.fromString(operation),resolved==null?null:Instant.parse(resolved),protection==null?null:Instant.parse(protection),list(row.get("final-rewards")).stream().map(DownedDirectory::map).map(reward->new DownedEpisode.Reward(uuid(reward,"character"),new java.math.BigInteger(text(reward,"experience")),new java.math.BigInteger(text(reward,"coins")))).toList(),Boolean.parseBoolean(String.valueOf(row.containsKey("published")?row.get("published"):false)));}
|
||||
private static Yaml yaml(){var options=new LoaderOptions();options.setAllowDuplicateKeys(false);options.setMaxAliasesForCollections(0);options.setCodePointLimit(1_048_576);return new Yaml(new SafeConstructor(options));}private static List<?> list(Object value){return value==null?List.of():(List<?>)value;}private static Map<?,?> map(Object value){return(Map<?,?>)value;}private static String text(Map<?,?> map,String key){Object value=map.get(key);if(!(value instanceof String text)||text.isBlank())throw new IllegalArgumentException(key);return text;}private static String optional(Map<?,?> map,String key){Object value=map.get(key);return value==null?null:text(map,key);}private static UUID uuid(Map<?,?> map,String key){return UUID.fromString(text(map,key));}
|
||||
private <T>CompletableFuture<T> submit(Callable<T> work){var result=new CompletableFuture<T>();synchronized(this){if(closed){result.completeExceptionally(new IOException("Downed directory closed"));return result;}pending++;}worker.execute(()->{try{result.complete(work.call());}catch(Throwable failure){result.completeExceptionally(failure);}finally{finished();}});return result;}private synchronized void finished(){pending--;if(closed&&pending==0)drained.complete(null);}public CompletionStage<Void> drained(){return drained.minimalCompletionStage();}@Override public synchronized void close(){closed=true;worker.shutdown();if(pending==0)drained.complete(null);}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Durable identity, anchor, attribution and single resolution for one lethal episode. */
|
||||
public record DownedEpisode(UUID id,UUID character,UUID player,UUID session,UUID world,
|
||||
double x,double y,double z,float yaw,float pitch,
|
||||
UUID entryWorld,double entryX,double entryY,double entryZ,float entryYaw,float entryPitch,
|
||||
Instant downedAt,Instant expiresAt,Attribution attribution,
|
||||
Phase phase,Outcome outcome,UUID outcomeOperation,
|
||||
Instant resolvedAt,Instant protectionUntil,List<Reward> finalRewards,boolean published){
|
||||
public enum Phase{PENDING,RESOLVED}
|
||||
public enum Outcome{REVIVED,FINAL_DEATH}
|
||||
public record Reward(UUID character,BigInteger experience,BigInteger coins){public Reward{Objects.requireNonNull(character);Objects.requireNonNull(experience);Objects.requireNonNull(coins);if(experience.signum()<0||coins.signum()<0)throw new IllegalArgumentException("Invalid downed reward");}}
|
||||
public record Attribution(UUID attacker,String cause,boolean playerDefeat,List<UUID> contributors,int victimLevel,BigInteger victimCoins){
|
||||
public Attribution(UUID attacker,String cause){this(attacker,cause,false,List.of(),0,BigInteger.ZERO);}
|
||||
public Attribution(UUID attacker,String cause,boolean playerDefeat){this(attacker,cause,playerDefeat,List.of(),0,BigInteger.ZERO);}
|
||||
public Attribution{if(cause==null||cause.isBlank()||victimLevel<0||victimCoins==null||victimCoins.signum()<0)throw new IllegalArgumentException("Invalid lethal attribution");contributors=List.copyOf(contributors);}
|
||||
}
|
||||
public DownedEpisode{Objects.requireNonNull(id);Objects.requireNonNull(character);Objects.requireNonNull(player);Objects.requireNonNull(session);Objects.requireNonNull(world);Objects.requireNonNull(entryWorld);Objects.requireNonNull(downedAt);Objects.requireNonNull(expiresAt);Objects.requireNonNull(attribution);Objects.requireNonNull(phase);finalRewards=List.copyOf(finalRewards);if(!Double.isFinite(x)||!Double.isFinite(y)||!Double.isFinite(z)||!Float.isFinite(yaw)||!Float.isFinite(pitch)||!Double.isFinite(entryX)||!Double.isFinite(entryY)||!Double.isFinite(entryZ)||!Float.isFinite(entryYaw)||!Float.isFinite(entryPitch)||!expiresAt.isAfter(downedAt))throw new IllegalArgumentException("Invalid downed episode");boolean resolved=phase==Phase.RESOLVED;if(resolved!=(outcome!=null&&outcomeOperation!=null&&resolvedAt!=null))throw new IllegalArgumentException("Invalid downed outcome");if(!resolved&&protectionUntil!=null||outcome==Outcome.FINAL_DEATH&&protectionUntil!=null||protectionUntil!=null&&protectionUntil.isBefore(resolvedAt))throw new IllegalArgumentException("Invalid downed protection");if((!resolved||outcome==Outcome.REVIVED)&&!finalRewards.isEmpty())throw new IllegalArgumentException("Invalid downed rewards");}
|
||||
}
|
||||
@@ -100,6 +100,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
private games.dmg.fantasystick.shop.RareMerchantController rareMerchantController;
|
||||
private games.dmg.fantasystick.shop.RareMarket rareMarket;
|
||||
private games.dmg.fantasystick.persistence.RareSettings rareSettings;
|
||||
private games.dmg.fantasystick.persistence.DownedSettings downedSettings;
|
||||
private games.dmg.fantasystick.book.CharacterBookController characterBooks;
|
||||
private games.dmg.fantasystick.persistence.CharacterStorage characters;
|
||||
private AdminCharacterRecovery characterRecovery;
|
||||
@@ -423,6 +424,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
public void attachArmorers(games.dmg.fantasystick.shop.FantasyArmorerDirectory directory,games.dmg.fantasystick.shop.FantasyArmorerController controller){if(closed||armorers!=null)throw new IllegalStateException("Armorers already attached or command closed");armorers=Objects.requireNonNull(directory);armorerController=Objects.requireNonNull(controller);}
|
||||
public void attachArmorMarket(games.dmg.fantasystick.shop.ArmorMarket market){if(closed||armorMarket!=null)throw new IllegalStateException("Armor market already attached or command closed");armorMarket=Objects.requireNonNull(market);}
|
||||
public void attachRareMarket(games.dmg.fantasystick.shop.RareMerchantDirectory directory,games.dmg.fantasystick.shop.RareMerchantController controller,games.dmg.fantasystick.shop.RareMarket market,games.dmg.fantasystick.persistence.RareSettings settings){if(closed||rareMerchants!=null)throw new IllegalStateException("Rare market already attached or command closed");rareMerchants=Objects.requireNonNull(directory);rareMerchantController=Objects.requireNonNull(controller);rareMarket=Objects.requireNonNull(market);rareSettings=Objects.requireNonNull(settings);}
|
||||
public void attachDownedSettings(games.dmg.fantasystick.persistence.DownedSettings settings){if(closed||downedSettings!=null)throw new IllegalStateException("Downed settings already attached or command closed");downedSettings=Objects.requireNonNull(settings);}
|
||||
|
||||
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
|
||||
if (closed) return true;
|
||||
@@ -921,6 +923,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
if (partyEconomySettings != null && games.dmg.fantasystick.persistence.PartyEconomySettings.keys().contains(args[1])) { partyEconomyConfiguration(sender,args); return; }
|
||||
if(gearSettings!=null&&games.dmg.fantasystick.persistence.GearSettings.keys().contains(args[1])){gearConfiguration(sender,args);return;}
|
||||
if(rareSettings!=null&&games.dmg.fantasystick.persistence.RareSettings.keys().contains(args[1])){rareConfiguration(sender,args);return;}
|
||||
if(downedSettings!=null&&games.dmg.fantasystick.persistence.DownedSettings.keys().contains(args[1])){downedConfiguration(sender,args);return;}
|
||||
if (coinSettings != null && games.dmg.fantasystick.persistence.CoinSettings.keys().contains(args[1])) { coinConfiguration(sender,args); return; }
|
||||
if (hardMobXpSettings != null && args[1].equals(games.dmg.fantasystick.persistence.HardMobXpSettings.KEY)) {
|
||||
hardMobXpConfiguration(sender, args); return;
|
||||
@@ -1554,6 +1557,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
|
||||
private void gearConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+gearSettings.value(key)+" (applies to the next armor restock only)");return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.GearSettings.Update> operation;try{operation=gearSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Armor market setting is invalid; variance is 0–100, prices are nonnegative, and positive stock minima cannot exceed maxima.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;nextTick.accept(()->{boolean applied=failure==null&&gearSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Armor market setting save failed; effective settings and the current catalog are unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+gearSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+" for the next automatic or administrative restock; the current catalog is unchanged.");});});}
|
||||
private void rareConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+rareSettings.value(key)+(key.endsWith("-healing-percent")?" (applies to future accepted uses)":" (applies to the next rare restock only)"));return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.RareSettings.Update> operation;try{operation=rareSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Rare setting is invalid; percentages are 0–100, values are nonnegative, and stock minima cannot exceed maxima.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;nextTick.accept(()->{boolean applied=failure==null&&rareSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Rare setting save failed; prior effective state is unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+rareSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+"; current catalog and accepted uses are unchanged.");});});}
|
||||
private void downedConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+downedSettings.value(key)+" (applies to future downed outcomes only)");return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.DownedSettings.Update> operation;try{operation=downedSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Downed setting is invalid; timeout must be positive and protection may be zero, both at most 365 days.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;nextTick.accept(()->{boolean applied=failure==null&&downedSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Downed setting save failed; prior effective state is unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+downedSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+"; existing deadlines are unchanged.");});});}
|
||||
|
||||
private void coinConfiguration(CommandSender sender,String[] args){String key=args[1];if(args.length==2){sender.sendMessage(key+"="+coinSettings.value(key)+" (applies to future creation or defeats only)");return;}java.util.concurrent.CompletionStage<games.dmg.fantasystick.persistence.CoinSettings.Update> operation;try{operation=coinSettings.set(key,args[2]);}catch(IllegalArgumentException invalid){sender.sendMessage("Coin setting is invalid; ranges must be ordered whole numbers from 0 through 2147483647.");return;}operation.whenComplete((saved,failure)->{if(failure!=null)report(null,"config-"+key,failure);if(closed)return;try{nextTick.accept(()->{if(closed)return;boolean applied=failure==null&&coinSettings.publish(saved);if(!sender.hasPermission(PERMISSION)||sender instanceof org.bukkit.entity.Player player&&!player.isOnline())return;if(failure!=null)sender.sendMessage("Coin configuration save failed; effective ranges are unchanged.");else if(!applied)sender.sendMessage("Saved request was superseded; effective "+key+"="+coinSettings.value(key)+".");else sender.sendMessage("Saved "+key+"="+saved.value()+" for future creation or defeats; existing balances and captured rewards are unchanged.");});}catch(RuntimeException rejected){report(null,"config-response",rejected);}});}
|
||||
|
||||
@@ -1694,6 +1698,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
keys.addAll(games.dmg.fantasystick.persistence.PartyEconomySettings.keys());
|
||||
keys.addAll(games.dmg.fantasystick.persistence.GearSettings.keys());
|
||||
keys.addAll(games.dmg.fantasystick.persistence.RareSettings.keys());
|
||||
keys.addAll(games.dmg.fantasystick.persistence.DownedSettings.keys());
|
||||
keys.addAll(games.dmg.fantasystick.persistence.CoinSettings.keys());
|
||||
keys.add(games.dmg.fantasystick.persistence.HardMobXpSettings.KEY);
|
||||
keys.addAll(games.dmg.fantasystick.persistence.AdventureQuestSettings.keys());
|
||||
@@ -1730,6 +1735,7 @@ public final class EquipmentAdminCommand implements TabExecutor, AutoCloseable {
|
||||
if(partyEconomySettings!=null&&games.dmg.fantasystick.persistence.PartyEconomySettings.keys().contains(args[1])){String current=partyEconomySettings.value(args[1]);String defaults=games.dmg.fantasystick.persistence.PartyEconomySettings.defaultValue(args[1]);return matching(current.equals(defaults)?List.of(current):List.of(current,defaults),args[2]);}
|
||||
if(gearSettings!=null&&games.dmg.fantasystick.persistence.GearSettings.keys().contains(args[1])){String current=gearSettings.value(args[1]);String defaults=games.dmg.fantasystick.persistence.GearSettings.defaultValue(args[1]);return matching(current.equals(defaults)?List.of(current):List.of(current,defaults),args[2]);}
|
||||
if(rareSettings!=null&&games.dmg.fantasystick.persistence.RareSettings.keys().contains(args[1])){String current=rareSettings.value(args[1]);String defaults=games.dmg.fantasystick.persistence.RareSettings.defaultValue(args[1]);return matching(current.equals(defaults)?List.of(current):List.of(current,defaults),args[2]);}
|
||||
if(downedSettings!=null&&games.dmg.fantasystick.persistence.DownedSettings.keys().contains(args[1])){String current=downedSettings.value(args[1]);String defaults=games.dmg.fantasystick.persistence.DownedSettings.defaultValue(args[1]);return matching(current.equals(defaults)?List.of(current):List.of(current,defaults),args[2]);}
|
||||
if(coinSettings!=null&&games.dmg.fantasystick.persistence.CoinSettings.keys().contains(args[1])){String current=coinSettings.value(args[1]);String defaults=games.dmg.fantasystick.persistence.CoinSettings.defaultValue(args[1]);return matching(current.equals(defaults)?List.of(current):List.of(current,defaults),args[2]);}
|
||||
if (hardMobXpSettings != null && args[1].equals(games.dmg.fantasystick.persistence.HardMobXpSettings.KEY)) {
|
||||
String current = hardMobXpSettings.value(); String defaults = games.dmg.fantasystick.persistence.HardMobXpSettings.DEFAULT;
|
||||
|
||||
@@ -147,7 +147,7 @@ public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void changed(PlayerInventorySlotChangeEvent event) { reconcile(event.getPlayer()); }
|
||||
public void changed(PlayerInventorySlotChangeEvent event){if(sessions.downed(event.getPlayer().getUniqueId()).isEmpty())reconcile(event.getPlayer());}
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR)
|
||||
public void join(org.bukkit.event.player.PlayerJoinEvent event) {
|
||||
@@ -172,7 +172,7 @@ public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void swap(org.bukkit.event.player.PlayerSwapHandItemsEvent event) {
|
||||
Player player = event.getPlayer();
|
||||
Player player = event.getPlayer();if(sessions.downed(player.getUniqueId()).isPresent()){event.setCancelled(true);return;}
|
||||
int slot = player.getInventory().getHeldItemSlot();
|
||||
if (reservedExchange(player, slot)) {
|
||||
event.setCancelled(true);
|
||||
@@ -189,6 +189,7 @@ public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void click(InventoryClickEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) return;
|
||||
if(sessions.downed(player.getUniqueId()).isPresent()){event.setCancelled(true);return;}
|
||||
if (ownInventory(player, event.getClickedInventory()) && event.getSlot() == 40
|
||||
&& (event.getClick() == ClickType.DROP || event.getClick() == ClickType.CONTROL_DROP)
|
||||
&& (event.getAction() == InventoryAction.DROP_ONE_SLOT || event.getAction() == InventoryAction.DROP_ALL_SLOT)
|
||||
@@ -317,6 +318,7 @@ public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void drag(InventoryDragEvent event) {
|
||||
if (!(event.getWhoClicked() instanceof Player player)) return;
|
||||
if(sessions.downed(player.getUniqueId()).isPresent()){event.setCancelled(true);return;}
|
||||
if (control(event.getOldCursor())) {
|
||||
event.setCancelled(true);
|
||||
if (pickupClaim(event.getOldCursor(), "control_move_") && event.getNewItems().size() == 1) {
|
||||
@@ -341,6 +343,7 @@ public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
|
||||
public void drop(org.bukkit.event.player.PlayerDropItemEvent event) {
|
||||
if(sessions.downed(event.getPlayer().getUniqueId()).isPresent()){event.setCancelled(true);return;}
|
||||
if (special(event.getItemDrop().getItemStack())) event.setCancelled(true);
|
||||
}
|
||||
|
||||
@@ -348,6 +351,7 @@ public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
// also run for RIGHT_CLICK_AIR / an existing block veto, without changing that veto.
|
||||
@EventHandler(priority = EventPriority.HIGHEST)
|
||||
public void use(org.bukkit.event.player.PlayerInteractEvent event) {
|
||||
if(sessions.downed(event.getPlayer().getUniqueId()).isPresent()){event.setUseItemInHand(org.bukkit.event.Event.Result.DENY);return;}
|
||||
boolean allowed = event.useItemInHand() != org.bukkit.event.Event.Result.DENY;
|
||||
boolean nativeControl=nativeUseControl.test(event.getPlayer(),event.getItem());
|
||||
if (special(event.getItem()) && (!nativeControl||event.getPlayer().isSneaking()) || active(event.getPlayer()) && forbiddenEquip(event.getItem())) {
|
||||
@@ -417,6 +421,7 @@ public final class EquipmentSessionEvents implements Listener, AutoCloseable {
|
||||
|
||||
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
|
||||
public void held(org.bukkit.event.player.PlayerItemHeldEvent event) {
|
||||
if(sessions.downed(event.getPlayer().getUniqueId()).isPresent()){event.setCancelled(true);return;}
|
||||
var draw = draws.get(event.getPlayer().getUniqueId());
|
||||
if (draw != null && draw.player() == event.getPlayer() && event.getPreviousSlot() != event.getNewSlot()) cancelDraw(draw);
|
||||
}
|
||||
|
||||
@@ -38,12 +38,15 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
public record Active(UUID player, UUID session, UUID character) { }
|
||||
public record ActiveCharacter(Active session, CharacterRecord record) { }
|
||||
public record SelectedControl(Active session, int slot, String ability) { }
|
||||
public record DefeatCapture(boolean playerDefeat,List<UUID> contributors,int victimLevel,BigInteger victimCoins){public DefeatCapture{contributors=List.copyOf(contributors);Objects.requireNonNull(victimCoins);}}
|
||||
|
||||
private final CharacterStorage characters;
|
||||
private final EquipmentSessionStore receipts;
|
||||
private Supplier<Duration> switchDelay;
|
||||
private java.util.function.BooleanSupplier roleplayDisabled = () -> false;
|
||||
private java.util.function.Predicate<UUID> pvpDefeat = ignored -> false;
|
||||
private java.util.function.Function<UUID,DefeatCapture> defeatCapture=ignored->new DefeatCapture(false,List.of(),0,BigInteger.ZERO);
|
||||
private java.util.function.Function<DownedEpisode,List<DownedEpisode.Reward>> downedRewardAllocation=ignored->List.of();
|
||||
private java.util.function.Function<DownedEpisode,CompletionStage<?>> downedDefeatRewards=ignored->CompletableFuture.completedStage(null);
|
||||
private java.util.function.Predicate<UUID> unavailableCharacter = ignored -> false;
|
||||
private java.util.function.Function<UUID,java.util.concurrent.CompletionStage<?>> partyDefeat =
|
||||
ignored -> java.util.concurrent.CompletableFuture.completedStage(null);
|
||||
@@ -57,6 +60,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
private SessionControls controls;
|
||||
private GearItems gear;
|
||||
private final CharacterSheets sheets = new CharacterSheets();
|
||||
private final games.dmg.fantasystick.items.TailBooks tails = new games.dmg.fantasystick.items.TailBooks();
|
||||
private final Map<UUID, Attempt> pending = new HashMap<>();
|
||||
private final Map<UUID, Attempt> owned = new HashMap<>();
|
||||
private final Map<UUID, Attempt> active = new HashMap<>();
|
||||
@@ -72,6 +76,9 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
private java.util.function.BooleanSupplier adventureMode = () -> false;
|
||||
private AdventureModeLease gameModes = new AdventureModeLease();
|
||||
private SessionVitals vitals;
|
||||
private DownedDirectory downedDirectory;
|
||||
private Supplier<Duration> downedTimeout=()->Duration.ofSeconds(300);
|
||||
private Consumer<DownedEpisode> downedPresentation=ignored->{};
|
||||
private boolean closeSweepFinished;
|
||||
private int persistenceOperations;
|
||||
private final CompletableFuture<Void> drained = new CompletableFuture<>();
|
||||
@@ -111,6 +118,15 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
Attempt recoveryOwner;
|
||||
org.bukkit.Location entryLocation;
|
||||
boolean defeated;
|
||||
boolean downing;
|
||||
boolean downedRelocation;
|
||||
DownedEpisode downed;
|
||||
DownedEpisode finalDowned;
|
||||
DownedEpisode resumedDowned;
|
||||
DownedEpisode resumedRevive;
|
||||
boolean reviveHealthReconciled;
|
||||
Instant downedProtectionUntil;
|
||||
boolean downedPvpDefeat;
|
||||
boolean deathResolved;
|
||||
boolean gearAcknowledged;
|
||||
boolean bookAttempted;
|
||||
@@ -185,10 +201,11 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
unavailableCharacter = Objects.requireNonNull(predicate);
|
||||
}
|
||||
|
||||
public synchronized void attachPvpDefeat(java.util.function.Predicate<UUID> predicate) {
|
||||
if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started");
|
||||
pvpDefeat = Objects.requireNonNull(predicate);
|
||||
}
|
||||
public synchronized void attachPvpDefeat(java.util.function.Predicate<UUID> predicate){attachDefeatCapture(player->new DefeatCapture(predicate.test(player),List.of(),0,BigInteger.ZERO));}
|
||||
public synchronized void attachDefeatCapture(java.util.function.Function<UUID,DefeatCapture> capture){if(!owned.isEmpty())throw new IllegalStateException("Sessions already started");defeatCapture=Objects.requireNonNull(capture);}
|
||||
public synchronized void attachDownedRewardAllocation(java.util.function.Function<DownedEpisode,List<DownedEpisode.Reward>> allocation){if(!owned.isEmpty())throw new IllegalStateException("Sessions already started");downedRewardAllocation=Objects.requireNonNull(allocation);}
|
||||
public synchronized void attachDownedDefeatRewards(java.util.function.Function<DownedEpisode,CompletionStage<?>> settlement){if(!owned.isEmpty())throw new IllegalStateException("Sessions already started");downedDefeatRewards=Objects.requireNonNull(settlement);}
|
||||
public synchronized List<DownedEpisode.Reward> finalRewards(DownedEpisode episode){return List.copyOf(downedRewardAllocation.apply(Objects.requireNonNull(episode)));}
|
||||
|
||||
public synchronized void attachPartyDefeat(java.util.function.Function<UUID,java.util.concurrent.CompletionStage<?>> mutation) {
|
||||
if (!owned.isEmpty()) throw new IllegalStateException("Sessions already started");
|
||||
@@ -244,6 +261,8 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
});
|
||||
}
|
||||
|
||||
private void persistReturn(Runnable action){try{nextTick.accept(action);}catch(RuntimeException ignored){}}
|
||||
|
||||
private void finishDrain() {
|
||||
if (closeSweepFinished && persistenceOperations == 0 && transitioning.isEmpty()) drained.complete(null);
|
||||
}
|
||||
@@ -270,7 +289,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
|
||||
private boolean availableForCharacterRecoveryNow(UUID character, UUID recipient) {
|
||||
if (closed || unavailableCharacter.test(character) || active.containsKey(recipient)
|
||||
if (closed || unavailableCharacter.test(character) || downedDirectory!=null&&downedDirectory.all().stream().anyMatch(value->value.character().equals(character)&&(value.phase()==DownedEpisode.Phase.PENDING||!value.published())) || active.containsKey(recipient)
|
||||
|| pending.containsKey(recipient) || transitioning.containsKey(recipient)
|
||||
|| owned.containsKey(recipient)) return false;
|
||||
return java.util.stream.Stream.of(active.values(), pending.values(), transitioning.values(), owned.values())
|
||||
@@ -296,10 +315,14 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized void attachDowned(DownedDirectory directory,Supplier<Duration> timeout,Consumer<DownedEpisode> presentation){if(closed||downedDirectory!=null)throw new IllegalStateException("Downed state already attached or sessions closed");downedDirectory=Objects.requireNonNull(directory);downedTimeout=Objects.requireNonNull(timeout);downedPresentation=Objects.requireNonNull(presentation);}
|
||||
|
||||
public synchronized Optional<DownedEpisode> downed(UUID player){var attempt=active.get(player);if(attempt!=null&&attempt.downed!=null)return Optional.of(attempt.downed);var directory=downedDirectory;return directory==null?Optional.empty():directory.all().stream().filter(value->value.player().equals(player)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst();}
|
||||
|
||||
/** Server-thread effect authorization: registry identity alone is not live custody. */
|
||||
public synchronized boolean current(Active session) {
|
||||
var attempt = active.get(session.player());
|
||||
return !closed && attempt != null && attempt.session.equals(session.session())
|
||||
return !closed && attempt != null && !attempt.downing && attempt.downed==null && attempt.session.equals(session.session())
|
||||
&& attempt.character.equals(session.character()) && attempt.player.isOnline() && attempt.record != null
|
||||
&& sheets.authorizes(attempt.player.getInventory().getItemInOffHand(), attempt.record);
|
||||
}
|
||||
@@ -465,7 +488,9 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
return Optional.of(new SelectedControl(new Active(attempt.owner, attempt.session, attempt.character), slot, ability));
|
||||
}
|
||||
|
||||
public synchronized void enter(Player player) {
|
||||
public synchronized void enter(Player player){enter(player,null);}
|
||||
|
||||
private void enter(Player player,DownedEpisode resumedDowned) {
|
||||
UUID owner = player.getUniqueId();
|
||||
if (closed) return;
|
||||
if (recoveryRecipients.contains(owner)) {
|
||||
@@ -496,15 +521,19 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
return;
|
||||
}
|
||||
var character = identity.orElseThrow().character();
|
||||
if(resumedDowned==null&&downedDirectory!=null)resumedDowned=downedDirectory.all().stream().filter(value->value.player().equals(owner)&&value.character().equals(character)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);
|
||||
if(resumedDowned!=null&&(!resumedDowned.player().equals(owner)||!resumedDowned.character().equals(character)||resumedDowned.phase()!=DownedEpisode.Phase.PENDING)){notice(owner,"DOWNED_RECOVERY_REQUIRED","Saved downed custody does not match the held sheet.");return;}
|
||||
if (characterRecoveries.containsKey(character)) {
|
||||
notice(owner, "CHARACTER_RECOVERY", "That character has unresolved administrative recovery custody.");
|
||||
return;
|
||||
}
|
||||
if (unavailableCharacter.test(character)) {
|
||||
notice(owner, "CHARACTER_IN_CUSTODY", "That character sheet is assigned to a dungeon boss and cannot be activated.");
|
||||
if (resumedDowned==null&&unavailableCharacter.test(character)) {
|
||||
notice(owner, "CHARACTER_IN_CUSTODY", "That character has unresolved external custody and cannot be activated.");
|
||||
return;
|
||||
}
|
||||
var attempt = new Attempt(player, owner, character);
|
||||
attempt.resumedDowned=resumedDowned;
|
||||
if(resumedDowned==null&&downedDirectory!=null)attempt.resumedRevive=downedDirectory.all().stream().filter(value->value.player().equals(owner)&&value.character().equals(character)&&value.phase()==DownedEpisode.Phase.RESOLVED&&value.outcome()==DownedEpisode.Outcome.REVIVED&&!value.published()).max(java.util.Comparator.comparing(DownedEpisode::resolvedAt)).orElse(null);
|
||||
attempt.sheetIdentity = identity.orElseThrow();
|
||||
if (adventureMode.getAsBoolean() && player.getGameMode() != org.bukkit.GameMode.ADVENTURE) {
|
||||
attempt.previousGameMode = player.getGameMode().name();
|
||||
@@ -556,12 +585,14 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
if (failure != null) { fail(attempt, failure); return; }
|
||||
var record = loaded.character().orElse(null);
|
||||
if (unavailableCharacter.test(attempt.character)) {
|
||||
refuse(attempt, "CHARACTER_IN_CUSTODY", "That character was assigned to a dungeon boss before activation completed."); return;
|
||||
if (attempt.resumedDowned==null&&unavailableCharacter.test(attempt.character)) {
|
||||
refuse(attempt, "CHARACTER_IN_CUSTODY", "That character entered unresolved external custody before activation completed."); return;
|
||||
}
|
||||
if (record == null || record.dead() || record.health().signum() <= 0) {
|
||||
refuse(attempt, "UNAVAILABLE_CHARACTER", "The saved character is missing, dead or has no health."); return;
|
||||
}
|
||||
if(attempt.resumedRevive!=null&&!attempt.reviveHealthReconciled){attempt.reviveHealthReconciled=true;var maximum=record.maximumHealth().min(NativeHealthLimit.read());if(record.health().compareTo(maximum)<0){characters.saveHealth(record.id(),record.revision(),maximum,maximum).whenComplete((saved,saveFailure)->schedule(attempt,()->loaded(attempt,new Loaded(saved==null?Optional.empty():saved,loaded.state()),saveFailure)));return;}}
|
||||
if(attempt.resumedDowned!=null&&(resolveWorld(attempt.player,attempt.resumedDowned.world())==null||resolveWorld(attempt.player,attempt.resumedDowned.entryWorld())==null)){refuse(attempt,"DOWNED_WORLD_UNAVAILABLE","Saved downed or return world is unavailable; custody remains unresolved.");return;}
|
||||
if (!sheets.authorizes(attempt.player.getInventory().getItemInOffHand(), record)
|
||||
|| attempt.sheetIdentity == null || !attempt.sheetIdentity.equals(
|
||||
sheets.identity(attempt.player.getInventory().getItemInOffHand()).orElse(null))) {
|
||||
@@ -591,14 +622,14 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
if (owned.values().stream().anyMatch(other -> attempt.character.equals(other.character))) {
|
||||
refuse(attempt, "CHARACTER_BUSY", "This character has an unresolved equipment session."); return;
|
||||
}
|
||||
attempt.claim = claims.tryClaim(attempt.owner, record).orElse(null);
|
||||
attempt.claim = (attempt.resumedDowned==null?claims.tryClaim(attempt.owner,record):claims.tryClaim(attempt.owner,record,attempt.resumedDowned.session())).orElse(null);
|
||||
if (attempt.claim == null) { refuse(attempt, "CHARACTER_BUSY", "This character or player already has a session."); return; }
|
||||
attempt.session = attempt.claim.sessionId();
|
||||
owned.put(attempt.owner, attempt);
|
||||
controls.create(record, attempt.owner, attempt.session); // Validate all nine controls before preparation/packing.
|
||||
if (vitals != null) attempt.ordinaryVitals = vitals.capture(attempt.player);
|
||||
attempt.saving = true;
|
||||
persist(() -> receipts.prepare(attempt.owner, attempt.session, attempt.character, attempt.previousGameMode, attempt.ordinaryVitals), (saved, error) -> {
|
||||
persist(() -> attempt.resumedDowned==null?receipts.prepare(attempt.owner,attempt.session,attempt.character,attempt.previousGameMode,attempt.ordinaryVitals):receipts.resume(attempt.owner,attempt.session,attempt.character,attempt.previousGameMode,attempt.ordinaryVitals), (saved, error) -> {
|
||||
attempt.saving = false;
|
||||
if (error != null) { attempt.uncertainSave = true; fail(attempt, error); return; }
|
||||
attempt.acknowledged = true;
|
||||
@@ -625,7 +656,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
boolean packed = false;
|
||||
try {
|
||||
var items = controls.create(record, attempt.owner, attempt.session);
|
||||
attempt.entryLocation = attempt.player.getLocation().clone(); // Server thread, before activation.
|
||||
attempt.entryLocation = attempt.resumedDowned==null?attempt.player.getLocation().clone():location(resolveWorld(attempt.player,attempt.resumedDowned.entryWorld()),attempt.resumedDowned.entryX(),attempt.resumedDowned.entryY(),attempt.resumedDowned.entryZ(),attempt.resumedDowned.entryYaw(),attempt.resumedDowned.entryPitch()); // Server thread, before activation.
|
||||
attempt.modeStarted = attempt.previousGameMode != null;
|
||||
if (!gameModes.enter(attempt.player, attempt.session, attempt.previousGameMode)) {
|
||||
attempt.modeStarted = false; // Returned refusal is not an uncertain setter exception.
|
||||
@@ -665,6 +696,9 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
attempt.presentationInstalled = true;
|
||||
try { presentation.activate(attempt.player, attempt.session, record); }
|
||||
catch (RuntimeException | LinkageError error) { withdrawPresentation(attempt); diagnostic(attempt, error); }
|
||||
if(attempt.resumedDowned!=null){attempt.downed=attempt.resumedDowned;attempt.downing=false;attempt.downedRelocation=true;try{var episode=attempt.resumedDowned;var anchor=location(resolveWorld(attempt.player,episode.world()),episode.x(),episode.y(),episode.z(),episode.yaw(),episode.pitch());if(!attempt.player.teleport(anchor))throw new IllegalStateException("Saved downed anchor teleport was refused");attempt.player.setHealth(1);downedPresentation.accept(episode);}finally{attempt.downedRelocation=false;}}
|
||||
else if(downedDirectory!=null)attempt.downedProtectionUntil=downedDirectory.all().stream().filter(value->value.player().equals(attempt.owner)&&value.character().equals(attempt.character)&&value.phase()==DownedEpisode.Phase.RESOLVED&&value.outcome()==DownedEpisode.Outcome.REVIVED&&value.protectionUntil()!=null&&clock.instant().isBefore(value.protectionUntil())).max(java.util.Comparator.comparing(DownedEpisode::resolvedAt)).map(DownedEpisode::protectionUntil).orElse(null);
|
||||
if(attempt.resumedRevive!=null){var recovered=attempt.resumedRevive;downedDirectory.publish(recovered.id(),recovered.outcomeOperation()).whenComplete((ignored,publishFailure)->{if(publishFailure!=null)diagnostic(attempt,publishFailure);});}
|
||||
}
|
||||
attempt.player.updateInventory();
|
||||
} catch (RuntimeException error) {
|
||||
@@ -721,6 +755,15 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
public synchronized void defeat(org.bukkit.event.entity.PlayerDeathEvent event) {
|
||||
if (closed || event.isCancelled()) return;
|
||||
UUID owner = event.getEntity().getUniqueId();
|
||||
var downedStore=downedDirectory;var pendingAttempt=active.get(owner);
|
||||
if(downedStore!=null&&pendingAttempt!=null){
|
||||
if(pendingAttempt.downing||pendingAttempt.downed!=null){event.setCancelled(true);event.setReviveHealth(1);return;}
|
||||
pendingAttempt.downing=true;var capturedDefeat=defeatCapture.apply(owner);pendingAttempt.downedPvpDefeat=capturedDefeat.playerDefeat();
|
||||
var location=pendingAttempt.player.getLocation().clone();var causing=event.getDamageSource().getCausingEntity();var damageType=event.getDamageSource().getDamageType();var attribution=new DownedEpisode.Attribution(causing==null?null:causing.getUniqueId(),damageType==null?"unknown":damageType.getKey().asString(),capturedDefeat.playerDefeat(),capturedDefeat.contributors(),capturedDefeat.victimLevel(),capturedDefeat.victimCoins());
|
||||
var work=downedStore.begin(pendingAttempt.character,pendingAttempt.owner,pendingAttempt.session,location.getWorld().getUID(),location.getX(),location.getY(),location.getZ(),location.getYaw(),location.getPitch(),pendingAttempt.entryLocation.getWorld().getUID(),pendingAttempt.entryLocation.getX(),pendingAttempt.entryLocation.getY(),pendingAttempt.entryLocation.getZ(),pendingAttempt.entryLocation.getYaw(),pendingAttempt.entryLocation.getPitch(),downedTimeout.get(),attribution);
|
||||
event.setCancelled(true);event.setReviveHealth(1);
|
||||
work.whenComplete((episode,failure)->persistReturn(()->{synchronized(EquipmentSessions.this){if(failure!=null){diagnostic(pendingAttempt,failure);notice(owner,"DOWNED_UNCERTAIN","Downed state could not be acknowledged; custody remains blocked.");return;}if(active.get(owner)!=pendingAttempt||!pendingAttempt.session.equals(episode.session()))return;pendingAttempt.downing=false;pendingAttempt.downed=episode;notice(owner,"DOWNED","§cYou are downed. Accept death or wait for Revive.");try{downedPresentation.accept(episode);}catch(RuntimeException presentationFailure){diagnostic(pendingAttempt,presentationFailure);}}}));return;
|
||||
}
|
||||
var attempt = active.remove(owner);
|
||||
if (attempt == null) {
|
||||
var transition = transitioning.get(owner);
|
||||
@@ -739,7 +782,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
boolean reserved = transitioning.putIfAbsent(attempt.owner, attempt) == null;
|
||||
// Submit first: any subsequent native getter/setter/notice can reenter disable, which
|
||||
// closes CharacterStorage. No dependent character work is submitted after this point.
|
||||
boolean loseCoins = pvpDefeat.test(owner);
|
||||
boolean loseCoins=defeatCapture.apply(owner).playerDefeat();
|
||||
persist(() -> characters.recordDeath(attempt.character, loseCoins), (dead, failure) -> {
|
||||
if (failure != null) { diagnostic(attempt, failure); conversionUncertain(attempt, "Death save failed or is uncertain"); return; }
|
||||
if (dead.isEmpty()) { conversionUncertain(attempt, "Character was missing or already dead; no new Tail authorized"); return; }
|
||||
@@ -794,6 +837,24 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
private static org.bukkit.World resolveWorld(Player player,UUID id){var current=player.getWorld();if(current!=null&&id.equals(current.getUID()))return current;return org.bukkit.Bukkit.getWorld(id);}
|
||||
private static org.bukkit.Location location(org.bukkit.World world,double x,double y,double z,float yaw,float pitch){return new org.bukkit.Location(world,x,y,z,yaw,pitch);}
|
||||
public synchronized boolean downedRelocation(UUID player){var attempt=active.get(player);return attempt!=null&&attempt.downedRelocation;}
|
||||
|
||||
public synchronized boolean downedProtected(UUID player){var attempt=active.get(player);return attempt!=null&&attempt.downed==null&&attempt.downedProtectionUntil!=null&&clock.instant().isBefore(attempt.downedProtectionUntil);}
|
||||
|
||||
/** Finish one durable Revive outcome on the exact retained active session. */
|
||||
public synchronized void reviveDowned(DownedEpisode episode,Consumer<Boolean> completion){Objects.requireNonNull(episode);Objects.requireNonNull(completion);if(episode.phase()!=DownedEpisode.Phase.RESOLVED||episode.outcome()!=DownedEpisode.Outcome.REVIVED){completion.accept(false);return;}var attempt=active.get(episode.player());if(attempt==null||attempt.downed==null||!attempt.downed.id().equals(episode.id())||!attempt.session.equals(episode.session())||!attempt.character.equals(episode.character())){completion.accept(false);return;}var expected=attempt.record.revision();var maximum=attempt.record.maximumHealth().min(NativeHealthLimit.read());characters.saveHealth(attempt.character,expected,maximum,maximum).whenComplete((saved,failure)->persistReturn(()->{synchronized(EquipmentSessions.this){if(failure!=null||saved==null||saved.isEmpty()||active.get(attempt.owner)!=attempt||attempt.downed==null||!attempt.downed.id().equals(episode.id())){if(failure!=null)diagnostic(attempt,failure);completion.accept(false);return;}var record=saved.orElseThrow();try{if(vitals!=null&&!record.revision().equals(attempt.record.revision()))vitals.updateProgress(attempt.player,attempt.session,attempt.record,record);attempt.record=record;attempt.downed=null;attempt.downing=false;attempt.downedProtectionUntil=episode.protectionUntil();double nativeMaximum=Objects.requireNonNull(attempt.player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue();attempt.player.setHealth(Math.min(nativeMaximum,record.health().doubleValue()));refreshControls(attempt,new Active(attempt.owner,attempt.session,attempt.character));attempt.player.closeInventory();notice(attempt.owner,"REVIVED","§aRevive restored your downed character.");completion.accept(true);}catch(RuntimeException publicationFailure){diagnostic(attempt,publicationFailure);completion.accept(false);}}}));}
|
||||
|
||||
/** Publish one already-durable final-death outcome through the existing restoration/Tail custody path. */
|
||||
public synchronized boolean finalizeDowned(DownedEpisode episode){Objects.requireNonNull(episode);if(episode.phase()!=DownedEpisode.Phase.RESOLVED||episode.outcome()!=DownedEpisode.Outcome.FINAL_DEATH)return false;var attempt=active.get(episode.player());if(attempt==null){persist(()->recordOfflineFinalDeath(episode),(dead,failure)->{if(failure!=null)diagnostic(new Failure(episode.player(),episode.session(),failure));else if(dead.isEmpty())diagnostic(new Failure(episode.player(),episode.session(),new IllegalStateException("Offline final death conflicted with saved character")));});return true;}if(attempt.downed==null||!attempt.downed.id().equals(episode.id())||!attempt.session.equals(episode.session())||!attempt.character.equals(episode.character()))return false;active.remove(attempt.owner,attempt);attempt.finalDowned=episode;attempt.downed=null;withdrawPresentation(attempt);attempt.defeated=true;boolean reserved=transitioning.putIfAbsent(attempt.owner,attempt)==null;boolean loseCoins=episode.attribution().playerDefeat();persist(()->characters.recordFinalDeath(attempt.character,attempt.record.revision(),episode.id(),episode.resolvedAt(),loseCoins),(dead,failure)->{if(failure!=null){diagnostic(attempt,failure);conversionUncertain(attempt,"Final death save failed or is uncertain");return;}if(dead.isEmpty()){conversionUncertain(attempt,"Character was missing or final death conflicted; no Tail authorized");return;}attempt.deathResolved=true;attempt.deathRecord=dead.orElseThrow();if(closed){conversionUncertain(attempt,"Shutdown before reward, party defeat and Tail conversion");return;}java.util.concurrent.CompletionStage<?> partyMutation=finalConsequences(episode);partyMutation.whenComplete((ignored,partyFailure)->{synchronized(EquipmentSessions.this){if(partyFailure!=null){diagnostic(attempt,partyFailure);conversionUncertain(attempt,"Party defeat mutation failed");return;}attempt.partyDefeatAcknowledged=true;queueTail(attempt);}});});try{var restored=restoreExit(attempt);if(restored==EquipmentStorage.RestoreResult.RESTORED){var retained=attempt.player.getInventory().getItemInOffHand();attempt.deathReference=copy(retained);attempt.deathNativeReference=nativeIdentity(retained);attempt.deathView=attempt.player.getOpenInventory();}double maximum=Objects.requireNonNull(attempt.player.getAttribute(org.bukkit.attribute.Attribute.MAX_HEALTH)).getValue();attempt.player.setHealth(maximum);notice(attempt.owner,"DEFEAT","§cYour character was defeated.");attempt.defeatReturnTeleport=true;try{if(!attempt.player.teleport(attempt.entryLocation.clone()))notice(attempt.owner,"DEFEAT_RETURN_FAILED","Return to the session entry location was refused; you remain here.");}finally{attempt.defeatReturnTeleport=false;if(!attempt.deliveryInvalidated&&owned.get(attempt.owner)==attempt&&attempt.player.isOnline())attempt.deathView=attempt.player.getOpenInventory();}}catch(RuntimeException failure){diagnostic(attempt,failure);conversionUncertain(attempt,"Native final-death transition failed; inspect retained equipment and death state");}finally{if(reserved)transitioning.remove(attempt.owner,attempt);finishDrain();}return true;}
|
||||
|
||||
private CompletionStage<Void> finalConsequences(DownedEpisode episode){var result=new CompletableFuture<Void>();try{nextTick.accept(()->{CompletionStage<?> work;try{work=downedDefeatRewards.apply(episode).thenCompose(ignored->partyDefeat.apply(episode.character()));}catch(RuntimeException failure){result.completeExceptionally(failure);return;}work.whenComplete((ignored,failure)->{if(failure==null)result.complete(null);else result.completeExceptionally(failure);});});}catch(RuntimeException rejected){result.completeExceptionally(rejected);}return result;}
|
||||
|
||||
private CompletionStage<Optional<CharacterRecord>> recordOfflineFinalDeath(DownedEpisode episode){return characters.find(episode.character()).thenCompose(found->{if(found.isEmpty())return CompletableFuture.completedStage(Optional.empty());var current=found.orElseThrow();return characters.recordFinalDeath(episode.character(),current.revision(),episode.id(),episode.resolvedAt(),episode.attribution().playerDefeat());}).thenCompose(dead->dead.isEmpty()?CompletableFuture.completedStage(dead):finalConsequences(episode).thenApply(ignored->dead));}
|
||||
|
||||
private void reconcileOfflineFinalDeath(Player player,DownedEpisode episode){persist(()->recordOfflineFinalDeath(episode),(dead,failure)->persistReturn(()->{synchronized(EquipmentSessions.this){if(failure!=null){diagnostic(new Failure(episode.player(),episode.session(),failure));return;}if(dead.isEmpty()||closed||!player.isOnline())return;var record=dead.orElseThrow();var current=player.getInventory().getItemInOffHand();var existing=tails.identify(current).orElse(null);if(existing!=null&&existing.characterId().equals(record.id())&&existing.deathId().equals(record.deathId())){downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((ignored,publishFailure)->{if(publishFailure!=null)diagnostic(new Failure(episode.player(),episode.session(),publishFailure));});return;}if(!sheets.authorizes(current,record)){notice(player.getUniqueId(),"DOWNED_RECOVERY_REQUIRED","Expired downed custody does not match the exact saved sheet; no native item was changed.");return;}try{player.getInventory().setItemInOffHand(tails.create(record));player.updateInventory();downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((ignored,publishFailure)->{if(publishFailure!=null)diagnostic(new Failure(episode.player(),episode.session(),publishFailure));});}catch(RuntimeException nativeFailure){diagnostic(new Failure(episode.player(),episode.session(),nativeFailure));notice(player.getUniqueId(),"DOWNED_RECOVERY_UNCERTAIN","Final-death Tail delivery was uncertain; retain inventory for inspection.");}}}));}
|
||||
|
||||
/** No automatic delivery after quit/respawn, including a reconnect of the same Player ID. */
|
||||
public synchronized void invalidateContext(UUID owner) {
|
||||
invalidateCursor(owner);
|
||||
@@ -872,6 +933,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
conversionUncertain(attempt, "Context changed during Tail write; delivery may already have happened"); return;
|
||||
}
|
||||
attempt.bookDelivered = true;
|
||||
publishDowned(attempt.finalDowned,attempt);
|
||||
release(attempt);
|
||||
sync(attempt);
|
||||
} catch (RuntimeException failure) {
|
||||
@@ -883,6 +945,8 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
private void publishDowned(DownedEpisode episode,Attempt attempt){if(episode==null||episode.published()||downedDirectory==null)return;downedDirectory.publish(episode.id(),episode.outcomeOperation()).whenComplete((ignored,failure)->{if(failure!=null)diagnostic(attempt,failure);});}
|
||||
|
||||
private boolean tailCustody(Attempt attempt) {
|
||||
var current = attempt.player.getInventory().getItemInOffHand();
|
||||
var authority = attempt.deathRecord == null ? attempt.record : attempt.deathRecord;
|
||||
@@ -1007,6 +1071,7 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
}
|
||||
|
||||
private void saveRemainingHealth(Attempt attempt) {
|
||||
if(attempt.downing||attempt.downed!=null){attempt.healthAcknowledged=true;return;}
|
||||
if (!attempt.vitalsStarted || attempt.defeated || attempt.healthSaveRequested) return;
|
||||
attempt.healthSaveRequested = true; // Failed/uncertain writes are not authority for an automatic replay.
|
||||
try {
|
||||
@@ -1166,7 +1231,11 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
public synchronized void recover(Player player) { recover(player, false); }
|
||||
|
||||
/** Join reconciliation: recover a pending receipt, otherwise request normal entry. */
|
||||
public synchronized void arrive(Player player) { recover(player, true); }
|
||||
public synchronized void arrive(Player player) {
|
||||
var directory=downedDirectory;
|
||||
if(directory!=null){var death=directory.all().stream().filter(value->value.player().equals(player.getUniqueId())&&value.phase()==DownedEpisode.Phase.RESOLVED&&value.outcome()==DownedEpisode.Outcome.FINAL_DEATH&&!value.published()).findFirst().orElse(null);if(death!=null){reconcileOfflineFinalDeath(player,death);return;}}
|
||||
recover(player,true);
|
||||
}
|
||||
|
||||
private void recover(Player player, boolean arrival) {
|
||||
UUID owner = player.getUniqueId();
|
||||
@@ -1207,7 +1276,8 @@ public final class EquipmentSessions implements AutoCloseable {
|
||||
var receipt = state.map(EquipmentSessionStore.State::pending).orElse(null);
|
||||
if (receipt == null) {
|
||||
if (attempt.arrival) {
|
||||
if (sheets.identify(attempt.player.getInventory().getItemInOffHand()).isPresent()) enter(attempt.player);
|
||||
var episode=downedDirectory==null?null:downedDirectory.all().stream().filter(value->value.player().equals(attempt.owner)&&value.phase()==DownedEpisode.Phase.PENDING).findFirst().orElse(null);
|
||||
if (sheets.identify(attempt.player.getInventory().getItemInOffHand()).isPresent()) enter(attempt.player,episode);
|
||||
else if (EquipmentSessionMarker.present(attempt.player) || hasRemnants(attempt.player)) {
|
||||
notice(attempt.owner, "NATIVE_RECOVERY_REQUIRED", "Native equipment remnants have no pending receipt; items were retained for inspection.");
|
||||
}
|
||||
|
||||
@@ -21,21 +21,20 @@ public final class SessionClaims implements AutoCloseable {
|
||||
* sheet possession, lifecycle, switching deadline and native preflight. This method does no file I/O.
|
||||
*/
|
||||
public synchronized Optional<Claim> tryClaim(UUID player, CharacterRecord character) {
|
||||
java.util.Objects.requireNonNull(player);
|
||||
java.util.Objects.requireNonNull(character);
|
||||
if (closed || character.dead() || character.health().signum() == 0
|
||||
|| players.containsKey(player) || characters.containsKey(character.id())) return Optional.empty();
|
||||
var claim = new Claim(player, character.id());
|
||||
players.put(player, claim);
|
||||
characters.put(character.id(), claim);
|
||||
return Optional.of(claim);
|
||||
return tryClaim(player,character,UUID.randomUUID());
|
||||
}
|
||||
|
||||
synchronized Optional<Claim> tryClaim(UUID player,CharacterRecord character,UUID session){
|
||||
java.util.Objects.requireNonNull(player);java.util.Objects.requireNonNull(character);java.util.Objects.requireNonNull(session);
|
||||
if(closed||character.dead()||character.health().signum()==0||players.containsKey(player)||characters.containsKey(character.id()))return Optional.empty();
|
||||
var claim=new Claim(player,character.id(),session);players.put(player,claim);characters.put(character.id(),claim);return Optional.of(claim);
|
||||
}
|
||||
|
||||
public final class Claim implements AutoCloseable {
|
||||
private final UUID player;
|
||||
private final UUID character;
|
||||
private final UUID session = UUID.randomUUID();
|
||||
private Claim(UUID player, UUID character) { this.player = player; this.character = character; }
|
||||
private final UUID session;
|
||||
private Claim(UUID player,UUID character,UUID session){this.player=player;this.character=character;this.session=session;}
|
||||
public UUID playerId() { return player; }
|
||||
public UUID characterId() { return character; }
|
||||
public UUID sessionId() { return session; }
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package games.dmg.fantasystick.shop;
|
||||
|
||||
import games.dmg.fantasystick.persistence.CharacterRecord;
|
||||
import games.dmg.fantasystick.persistence.CharacterStorage;
|
||||
import games.dmg.fantasystick.session.EquipmentSessions;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import org.bukkit.entity.Player;
|
||||
|
||||
/** Recoverable one-Core-to-one-ordinary-point exchange for the exact active character. */
|
||||
public final class RareMagicCoreService {
|
||||
public enum Status { APPLIED, NOT_AVAILABLE, STALE, FAILED }
|
||||
public record Outcome(Status status, Optional<CharacterRecord> record) { }
|
||||
private record Context(EquipmentSessions.Active active, CharacterRecord record) { }
|
||||
|
||||
private final RareInventoryDirectory inventory;
|
||||
private final CharacterStorage characters;
|
||||
private final EquipmentSessions sessions;
|
||||
private final Consumer<Runnable> nextTick;
|
||||
private final Consumer<Throwable> failures;
|
||||
|
||||
public RareMagicCoreService(RareInventoryDirectory inventory, CharacterStorage characters,
|
||||
EquipmentSessions sessions, Consumer<Runnable> nextTick,
|
||||
Consumer<Throwable> failures) {
|
||||
this.inventory=Objects.requireNonNull(inventory);this.characters=Objects.requireNonNull(characters);
|
||||
this.sessions=Objects.requireNonNull(sessions);this.nextTick=Objects.requireNonNull(nextTick);
|
||||
this.failures=Objects.requireNonNull(failures);
|
||||
}
|
||||
|
||||
public BigInteger quantity(UUID character){return inventory.quantity(character,RareProduct.MAGIC_CORE);}
|
||||
|
||||
public void use(Player player,Consumer<Outcome> result){
|
||||
var captured=context(player).orElse(null);
|
||||
if(captured==null){result.accept(new Outcome(Status.STALE,Optional.empty()));return;}
|
||||
BigInteger quantity=quantity(captured.record().id());
|
||||
if(quantity.signum()<=0){result.accept(new Outcome(Status.NOT_AVAILABLE,Optional.of(captured.record())));return;}
|
||||
UUID operation=UUID.randomUUID();
|
||||
inventory.reserveUse(captured.record().id(),RareProduct.MAGIC_CORE,operation,quantity).whenComplete((reservation,reserveFailure)->{
|
||||
if(reserveFailure!=null){fail(reserveFailure,result);return;}
|
||||
if(reservation.status()!=RareInventoryDirectory.UseStatus.RESERVED){publish(()->result.accept(new Outcome(reservation.status()==RareInventoryDirectory.UseStatus.NOT_AVAILABLE?Status.NOT_AVAILABLE:Status.STALE,Optional.empty())));return;}
|
||||
characters.consumeMagicCore(captured.record().id(),captured.record().revision(),operation).whenComplete((credit,creditFailure)->complete(player,captured,operation,credit,creditFailure,result));
|
||||
});
|
||||
}
|
||||
|
||||
/** Resolve interrupted credits from authoritative character proof without publishing a second point. */
|
||||
public void install(){for(var use:inventory.unresolvedUses()){if(!use.product().equals(RareProduct.MAGIC_CORE.id()))continue;characters.find(use.character()).whenComplete((record,failure)->{if(failure!=null){report(failure);return;}boolean applied=record.isPresent()&&record.orElseThrow().rewardReceipts().contains(use.operation());var work=applied?inventory.commitUse(use.operation()):inventory.refundUse(use.operation());work.exceptionally(problem->{report(problem);return RareInventoryDirectory.UseStatus.RESERVED;});});}}
|
||||
|
||||
private void complete(Player player,Context captured,UUID operation,CharacterStorage.MagicCore credit,Throwable failure,Consumer<Outcome> result){
|
||||
if(failure!=null||credit==null){if(failure!=null)report(failure);refund(operation,()->result.accept(new Outcome(Status.FAILED,Optional.empty())));return;}
|
||||
if(credit.status()!=CharacterStorage.MagicCoreStatus.APPLIED&&credit.status()!=CharacterStorage.MagicCoreStatus.DUPLICATE){var status=credit.status()==CharacterStorage.MagicCoreStatus.UNAVAILABLE?Status.NOT_AVAILABLE:Status.STALE;refund(operation,()->result.accept(new Outcome(status,credit.record())));return;}
|
||||
publish(()->{boolean acknowledged=false;try{var current=context(player);acknowledged=current.isPresent()&¤t.orElseThrow().active().session().equals(captured.active().session())&&(credit.status()==CharacterStorage.MagicCoreStatus.DUPLICATE||sessions.acknowledgeProgress(captured.active(),captured.record().revision(),credit.record().orElseThrow()));}catch(RuntimeException uncertain){report(uncertain);}boolean currentSession=acknowledged;inventory.commitUse(operation).whenComplete((ignored,commitFailure)->{if(commitFailure!=null){report(commitFailure);publish(()->result.accept(new Outcome(Status.FAILED,credit.record())));}else publish(()->result.accept(new Outcome(currentSession?Status.APPLIED:Status.STALE,credit.record())));});});
|
||||
}
|
||||
|
||||
private void refund(UUID operation,Runnable after){inventory.refundUse(operation).whenComplete((ignored,failure)->{if(failure!=null)report(failure);publish(after);});}
|
||||
private Optional<Context> context(Player player){var active=sessions.active(player.getUniqueId()).filter(sessions::current).orElse(null);var record=active==null?null:sessions.currentRecord(active).filter(value->!value.dead()).orElse(null);return record==null?Optional.empty():Optional.of(new Context(active,record));}
|
||||
private void fail(Throwable failure,Consumer<Outcome> result){report(failure);publish(()->result.accept(new Outcome(Status.FAILED,Optional.empty())));}
|
||||
private void publish(Runnable action){try{nextTick.accept(action);}catch(RuntimeException failure){report(failure);}}
|
||||
private void report(Throwable failure){try{failures.accept(failure);}catch(RuntimeException ignored){}}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ public enum RareProduct {
|
||||
LESSER_HEALTH_POTION("lesser-health-potion", "Lesser Health Potion", 50, 10, 25),
|
||||
HEALTH_POTION("health-potion", "Health Potion", 150, 5, 50),
|
||||
GREATER_HEALTH_POTION("greater-health-potion", "Greater Health Potion", 500, 2, 100),
|
||||
RESKILL("reskill", "Reskill", 2000, 1, null);
|
||||
RESKILL("reskill", "Reskill", 2000, 1, null),
|
||||
MAGIC_CORE("magic-core", "Magic Core", 3000, 3, null);
|
||||
|
||||
private final String id;
|
||||
private final String displayName;
|
||||
|
||||
@@ -44,6 +44,11 @@ rare-greater-health-potion-healing-percent: 100
|
||||
rare-price-reskill: 2000
|
||||
rare-stock-reskill-min: 0
|
||||
rare-stock-reskill-max: 1
|
||||
rare-price-magic-core: 3000
|
||||
rare-stock-magic-core-min: 0
|
||||
rare-stock-magic-core-max: 3
|
||||
downed-timeout-seconds: 300
|
||||
revive-downed-invulnerability-seconds: 5
|
||||
sheet-resource-pack-url: ''
|
||||
sheet-resource-pack-sha1: ''
|
||||
|
||||
|
||||
@@ -488,9 +488,9 @@ class CombatExperienceNativeTest {
|
||||
var source = mock(org.bukkit.damage.DamageSource.class);
|
||||
var defeat = new org.bukkit.event.entity.PlayerDeathEvent(b.player, source, new ArrayList<>(), 0,
|
||||
net.kyori.adventure.text.Component.text("defeat"), true);
|
||||
f.dispatcher.accept(defeat); settle(f); settle(f); settle(f);
|
||||
f.dispatcher.accept(defeat);settle(f);var downed=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&downed.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var captured=downed.all().getFirst().attribution();assertTrue(captured.contributors().contains(a.core.record.id()),"Originating character attribution survives the wait");assertEquals(java.math.BigInteger.ZERO,record(f,a).experience(),"Downing alone grants no defeat XP");assertEquals(victimCoins,record(f,b).coins(),"Downing alone loses no victim coins");DownedSessionNativeTest.acceptDeath(f,b);settle(f);settle(f);settle(f);for(int attempt=0;attempt<120&&record(f,a).experience().signum()==0;attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}
|
||||
assertTrue(defeat.isCancelled());
|
||||
assertEquals(java.math.BigInteger.TEN, record(f, a).experience(), "Level-one fantasy defeat supplies a ten-XP pool");
|
||||
assertEquals(java.math.BigInteger.TEN,record(f,a).experience(),"Level-one fantasy defeat supplies a ten-XP pool");
|
||||
assertEquals(attackerCoins.add(victimCoins), record(f, a).coins());
|
||||
assertTrue(record(f, b).dead());
|
||||
assertEquals(java.math.BigInteger.ZERO, record(f, b).coins(), "PvP defeat binds and zeroes the full saved balance");
|
||||
|
||||
@@ -31,11 +31,13 @@ class DefeatHealthDeliveryNativeTest {
|
||||
a.nativePlayer.queueHealthUpdatePacket = queued;
|
||||
var death = death(a);
|
||||
f.dispatcher.accept(death);
|
||||
DownedSessionNativeTest.acceptDeath(f,a);
|
||||
if (a.nativePlayer.queuedHealthUpdatePacket != null) sent.add(a.nativePlayer.queuedHealthUpdatePacket);
|
||||
a.nativePlayer.queueHealthUpdatePacket = false;
|
||||
PartyLifecycleNativeTest.directory(f).defeat(java.util.UUID.randomUUID()).join();
|
||||
f.awaitCharacterAndReceipt(a);
|
||||
PartyBookNativeTest.drain(f);
|
||||
DownedSessionNativeTest.awaitTail(f,a);
|
||||
assertTrue(death.isCancelled());
|
||||
assertEquals(a.maximumHealth.getValue(), a.player.getHealth());
|
||||
assertEquals(entry, a.player.getLocation());
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package games.dmg.fantasystick;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class DownedSessionNativeTest{
|
||||
@TempDir Path data;
|
||||
@BeforeAll static void bootstrap()throws Exception{NativeRuntime.bootstrap();}
|
||||
@Test void registeredAdminConfigurationReadsCompletesValidatesAndPublishesDownedPolicies()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var sender=new EquipmentAdminCommandNativeTest.Sender();assertEquals(java.util.List.of("downed-timeout-seconds"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed"}));assertEquals(java.util.List.of("300"),f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds",""}));f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds"});assertTrue(sender.messages.getLast().contains("=300"));int before=sender.messages.size();f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds","240"});while(sender.messages.size()==before){var task=f.tasks.poll(5,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(task);task.run();}assertTrue(sender.messages.getLast().contains("=240"));var settings=(games.dmg.fantasystick.persistence.DownedSettings)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedSettings");assertEquals(java.time.Duration.ofSeconds(240),settings.timeout());f.command.execute(sender.port,"fantasystick",new String[]{"config","downed-timeout-seconds","0"});assertTrue(sender.messages.getLast().contains("invalid"));assertEquals(java.time.Duration.ofSeconds(240),settings.timeout());f.command.execute(sender.port,"fantasystick",new String[]{"config","revive-downed-invulnerability-seconds","5","extra"});assertTrue(sender.messages.getLast().contains("Usage"));sender.allowed=false;assertTrue(f.command.tabComplete(sender.port,"fantasystick",new String[]{"config","downed"}).isEmpty());assertTrue(java.nio.file.Files.readString(data.resolve("config.yml")).contains("downed-timeout-seconds: 240"));}
|
||||
}
|
||||
@Test void directProjectileOngoingAndEnvironmentalLethalCausesEnterTheSameDurablePhase()throws Exception{
|
||||
var types=java.util.List.of(org.bukkit.damage.DamageType.PLAYER_ATTACK,org.bukkit.damage.DamageType.ARROW,org.bukkit.damage.DamageType.ON_FIRE,org.bukkit.damage.DamageType.FALL);int index=0;for(var type:types){var directory=data.resolve("cause-"+index++);java.nio.file.Files.createDirectories(directory);try(var f=new FantasyStickLifecycleNativeTest.Fixture(directory)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(directory);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.health=0;var death=death(actor,type);f.dispatcher.accept(death);var downed=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&downed.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(death.isCancelled());assertEquals(type.getKey().asString(),downed.all().getFirst().attribution().cause());}}
|
||||
}
|
||||
@Test void nativeLethalOutcomeEntersDurableDownedPhaseWithoutFinalDeathOrTail()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.location.add(7,0,3);var anchor=actor.core.location.clone();actor.core.health=0;var death=death(actor);f.dispatcher.accept(death);actor.player.setHealth(death.getReviveHealth());var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&directory.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(death.isCancelled());assertEquals(1d,actor.player.getHealth());var episode=directory.all().getFirst();assertEquals(actor.core.record.id(),episode.character());assertEquals(actor.core.id,episode.player());assertEquals(anchor.getWorld().getUID(),episode.world());assertEquals(anchor.getX(),episode.x());assertEquals(games.dmg.fantasystick.session.DownedEpisode.Phase.PENDING,episode.phase());var characters=(games.dmg.fantasystick.persistence.CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");assertFalse(characters.find(actor.core.record.id()).join().orElseThrow().dead());assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType());var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");var active=sessions.active(actor.core.id).orElseThrow();assertFalse(sessions.current(active));assertTrue(sessions.downed(actor.core.id).isPresent());}
|
||||
}
|
||||
@Test void claimedReviveRestoresFullHealthInPlaceAndAddsBoundedDamageProtection()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.location.add(4,0,2);var anchor=actor.core.location.clone();actor.core.health=0;f.dispatcher.accept(death(actor));var controller=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedController");var outcome=new java.util.concurrent.atomic.AtomicReference<games.dmg.fantasystick.session.DownedController.RescueStatus>();for(int attempt=0;attempt<80&&!controller.downed(actor.player);attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}controller.revive(actor.player,java.time.Duration.ofSeconds(5),outcome::set);for(int attempt=0;attempt<80&&outcome.get()==null;attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertEquals(games.dmg.fantasystick.session.DownedController.RescueStatus.APPLIED,outcome.get());assertEquals(actor.maximumHealth.getValue(),actor.player.getHealth());assertEquals(anchor,actor.player.getLocation());var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");assertTrue(sessions.current(sessions.active(actor.core.id).orElseThrow()));assertTrue(sessions.downedProtected(actor.core.id));assertFalse(new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow().dead());var damage=org.mockito.Mockito.mock(org.bukkit.event.entity.EntityDamageEvent.class);org.mockito.Mockito.when(damage.getEntity()).thenReturn(actor.player);controller.damage(damage);org.mockito.Mockito.verify(damage).setCancelled(true);assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType());sessions.exit(actor.player);f.awaitCharacterAndReceipt(actor);sessions.arrive(actor.player);for(int attempt=0;attempt<120&&sessions.active(actor.core.id).isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(sessions.downedProtected(actor.core.id),"Reconnect retains the original absolute protection deadline");}
|
||||
}
|
||||
@Test void downedFreezeCancelsMotionCombatHealingHungerItemsAndInventoryMutation()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.health=0;f.dispatcher.accept(death(actor));var controller=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedController");for(int attempt=0;attempt<80&&(!controller.downed(actor.player)||actor.inventories.isEmpty());attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}org.mockito.Mockito.verify(actor.player).setGravity(false);var from=actor.core.location.clone();var to=from.clone().add(1,0,0);var move=org.mockito.Mockito.mock(org.bukkit.event.player.PlayerMoveEvent.class);org.mockito.Mockito.when(move.getPlayer()).thenReturn(actor.player);org.mockito.Mockito.when(move.getFrom()).thenReturn(from);org.mockito.Mockito.when(move.getTo()).thenReturn(to);controller.move(move);org.mockito.Mockito.verify(move).setTo(from);var velocity=org.mockito.Mockito.mock(org.bukkit.event.player.PlayerVelocityEvent.class);org.mockito.Mockito.when(velocity.getPlayer()).thenReturn(actor.player);controller.velocity(velocity);org.mockito.Mockito.verify(velocity).setCancelled(true);var attack=org.mockito.Mockito.mock(org.bukkit.event.entity.EntityDamageByEntityEvent.class);org.mockito.Mockito.when(attack.getDamager()).thenReturn(actor.player);controller.attack(attack);org.mockito.Mockito.verify(attack).setCancelled(true);var heal=org.mockito.Mockito.mock(org.bukkit.event.entity.EntityRegainHealthEvent.class);org.mockito.Mockito.when(heal.getEntity()).thenReturn(actor.player);controller.heal(heal);org.mockito.Mockito.verify(heal).setCancelled(true);var hunger=org.mockito.Mockito.mock(org.bukkit.event.entity.FoodLevelChangeEvent.class);org.mockito.Mockito.when(hunger.getEntity()).thenReturn(actor.player);controller.hunger(hunger);org.mockito.Mockito.verify(hunger).setCancelled(true);var consume=org.mockito.Mockito.mock(org.bukkit.event.player.PlayerItemConsumeEvent.class);org.mockito.Mockito.when(consume.getPlayer()).thenReturn(actor.player);controller.consume(consume);org.mockito.Mockito.verify(consume).setCancelled(true);var old=actor.core.inventory.getItem(4).clone();actor.core.inventory.setItem(4,new org.bukkit.inventory.ItemStack(org.bukkit.Material.DIRT));var change=new io.papermc.paper.event.player.PlayerInventorySlotChangeEvent(actor.player,4,old,actor.core.inventory.getItem(4));((games.dmg.fantasystick.session.EquipmentSessionEvents)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessionEvents")).changed(change);assertTrue(((games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions")).active(actor.core.id).isPresent());controller.slot(change);var task=f.tasks.poll(1,java.util.concurrent.TimeUnit.SECONDS);assertNotNull(task);task.run();assertEquals(old,actor.core.inventory.getItem(4));}
|
||||
}
|
||||
@Test void reconnectBeforeExpiryRebindsTheExactSessionAtItsSavedAnchor()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);var worldId=UUID.randomUUID();org.mockito.Mockito.when(actor.world.getUID()).thenReturn(worldId);f.activate(actor);actor.core.location.add(6,1,-2);var anchor=actor.core.location.clone();actor.core.health=0;f.dispatcher.accept(death(actor));var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&directory.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var episode=directory.all().getFirst();var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");sessions.exit(actor.player);f.awaitCharacterAndReceipt(actor);actor.core.location.add(40,0,0);sessions.arrive(actor.player);for(int attempt=0;attempt<160&&(sessions.active(actor.core.id).isEmpty()||sessions.downed(actor.core.id).isEmpty());attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(sessions.active(actor.core.id).isPresent(),actor.messages.toString());var rebound=sessions.active(actor.core.id).orElseThrow();assertEquals(episode.session(),rebound.session());assertEquals(episode.id(),sessions.downed(actor.core.id).orElseThrow().id());assertEquals(anchor,actor.player.getLocation());assertFalse(sessions.current(rebound));}
|
||||
}
|
||||
@Test void acknowledgedReviveInterruptedBeforePublicationReconcilesOnceOnReconnect()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());var characters=(games.dmg.fantasystick.persistence.CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var initial=characters.find(actor.core.record.id()).join().orElseThrow();characters.saveHealth(initial.id(),initial.revision(),java.math.BigDecimal.valueOf(4),initial.maximumHealth()).join();f.activate(actor);actor.core.health=0;f.dispatcher.accept(death(actor));var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&directory.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var episode=directory.all().getFirst();var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");sessions.exit(actor.player);f.awaitCharacterAndReceipt(actor);var resolved=directory.claim(episode.id(),games.dmg.fantasystick.session.DownedEpisode.Outcome.REVIVED,UUID.randomUUID(),java.time.Duration.ofSeconds(5)).join().episode().orElseThrow();assertFalse(resolved.published());sessions.arrive(actor.player);for(int attempt=0;attempt<160&&(sessions.active(actor.core.id).isEmpty()||!directory.find(actor.core.record.id()).join().orElseThrow().published());attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(sessions.current(sessions.active(actor.core.id).orElseThrow()));assertEquals(actor.maximumHealth.getValue(),actor.player.getHealth());var saved=characters.find(actor.core.record.id()).join().orElseThrow();assertEquals(0,saved.maximumHealth().compareTo(saved.health()));assertTrue(directory.find(actor.core.record.id()).join().orElseThrow().published());assertTrue(sessions.downedProtected(actor.core.id));}
|
||||
}
|
||||
@Test void offlineFinalizationRecordsOriginalTimeAndReconcilesTheExactSheet()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.health=0;f.dispatcher.accept(death(actor));var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&directory.all().isEmpty();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var episode=directory.all().getFirst();var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");sessions.exit(actor.player);var resolved=directory.claim(episode.id(),games.dmg.fantasystick.session.DownedEpisode.Outcome.FINAL_DEATH,UUID.randomUUID(),java.time.Duration.ZERO).join().episode().orElseThrow();assertTrue(sessions.finalizeDowned(resolved));for(int attempt=0;attempt<120&&!new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow().dead();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var dead=new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow();assertEquals(resolved.resolvedAt(),dead.diedAt());assertEquals(episode.id(),dead.deathId());assertEquals(org.bukkit.Material.PAPER,actor.core.inventory.getItemInOffHand().getType());sessions.arrive(actor.player);for(int attempt=0;attempt<80&&actor.core.inventory.getItemInOffHand().getType()!=org.bukkit.Material.WRITTEN_BOOK;attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType(),actor.messages.toString());for(int attempt=0;attempt<80&&!directory.find(actor.core.record.id()).join().orElseThrow().published();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(directory.find(actor.core.record.id()).join().orElseThrow().published());}
|
||||
}
|
||||
@Test void deathMenuAcceptanceFinalizesTheSameEpisodeAndDeliversOneTail()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);org.mockito.Mockito.when(actor.world.getUID()).thenReturn(UUID.randomUUID());f.activate(actor);actor.core.health=0;f.dispatcher.accept(death(actor));var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downed");for(int attempt=0;attempt<80&&(directory.all().isEmpty()||actor.inventories.isEmpty());attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var episode=directory.all().getFirst();var menu=actor.inventories.getLast();assertTrue(plain(menu.getItem(11)).contains("Accept Death"));assertTrue(plain(menu.getItem(13)).contains("Phoenix Down"));assertTrue(plain(menu.getItem(15)).contains("Wait for Revive"));var view=org.mockito.Mockito.mock(org.bukkit.inventory.InventoryView.class);org.mockito.Mockito.when(view.getTopInventory()).thenReturn(menu);var click=org.mockito.Mockito.mock(org.bukkit.event.inventory.InventoryClickEvent.class);org.mockito.Mockito.when(click.getView()).thenReturn(view);org.mockito.Mockito.when(click.getWhoClicked()).thenReturn(actor.player);org.mockito.Mockito.when(click.getRawSlot()).thenReturn(11);var controller=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"downedController");controller.click(click);controller.click(click);for(int attempt=0;attempt<120&&!new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow().dead();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}PartyLifecycleNativeTest.directory(f).defeat(UUID.randomUUID()).join();f.awaitCharacterAndReceipt(actor);PartyBookNativeTest.drain(f);var dead=new games.dmg.fantasystick.persistence.YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow();assertTrue(dead.dead());assertEquals(episode.id(),dead.deathId());assertEquals(games.dmg.fantasystick.session.DownedEpisode.Outcome.FINAL_DEATH,directory.find(dead.id()).join().orElseThrow().outcome());for(int attempt=0;attempt<80&&!directory.find(dead.id()).join().orElseThrow().published();attempt++){var task=f.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertTrue(directory.find(dead.id()).join().orElseThrow().published());assertEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType());}
|
||||
}
|
||||
static void awaitTail(FantasyStickLifecycleNativeTest.Fixture fixture,FantasyStickLifecycleNativeTest.Actor actor)throws Exception{for(int attempt=0;attempt<160&&actor.core.inventory.getItemInOffHand().getType()!=org.bukkit.Material.WRITTEN_BOOK;attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}assertEquals(org.bukkit.Material.WRITTEN_BOOK,actor.core.inventory.getItemInOffHand().getType());}
|
||||
static void acceptDeath(FantasyStickLifecycleNativeTest.Fixture fixture,FantasyStickLifecycleNativeTest.Actor actor)throws Exception{var directory=(games.dmg.fantasystick.session.DownedDirectory)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"downed");for(int attempt=0;attempt<80&&(directory.all().stream().noneMatch(value->value.player().equals(actor.core.id)&&value.phase()==games.dmg.fantasystick.session.DownedEpisode.Phase.PENDING)||actor.inventories.isEmpty());attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var menu=actor.inventories.getLast();var view=org.mockito.Mockito.mock(org.bukkit.inventory.InventoryView.class);org.mockito.Mockito.when(view.getTopInventory()).thenReturn(menu);var click=org.mockito.Mockito.mock(org.bukkit.event.inventory.InventoryClickEvent.class);org.mockito.Mockito.when(click.getView()).thenReturn(view);org.mockito.Mockito.when(click.getWhoClicked()).thenReturn(actor.player);org.mockito.Mockito.when(click.getRawSlot()).thenReturn(11);((games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"downedController")).click(click);for(int attempt=0;attempt<120&&directory.all().stream().anyMatch(value->value.player().equals(actor.core.id)&&value.phase()==games.dmg.fantasystick.session.DownedEpisode.Phase.PENDING);attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"sessions");for(int attempt=0;attempt<80&&sessions.active(actor.core.id).isPresent();attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}}
|
||||
private static String plain(org.bukkit.inventory.ItemStack item){return net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(item.getItemMeta().displayName());}
|
||||
private static org.bukkit.event.entity.PlayerDeathEvent death(FantasyStickLifecycleNativeTest.Actor actor){return death(actor,org.bukkit.damage.DamageType.GENERIC);}
|
||||
private static org.bukkit.event.entity.PlayerDeathEvent death(FantasyStickLifecycleNativeTest.Actor actor,org.bukkit.damage.DamageType type){var source=new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(type)));return new org.bukkit.event.entity.PlayerDeathEvent(actor.player,source,new ArrayList<>(),0,net.kyori.adventure.text.Component.empty(),true);}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ class FantasyHealthNativeTest {
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.OUT_OF_WORLD)));
|
||||
var death = new org.bukkit.event.entity.PlayerDeathEvent(a.player, source, new java.util.ArrayList<>(), 0,
|
||||
net.kyori.adventure.text.Component.empty(), true);
|
||||
f.dispatcher.accept(death); assertTrue(death.isCancelled());
|
||||
f.dispatcher.accept(death); DownedSessionNativeTest.acceptDeath(f,a); assertTrue(death.isCancelled());
|
||||
for(int attempt=0;attempt<80&&a.core.inventory.getItemInOffHand().getType()!=org.bukkit.Material.WRITTEN_BOOK;attempt++){var task=f.tasks.poll(20,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}
|
||||
assertEquals(1, receivedDust(a, org.bukkit.Color.RED), "Aura opt-out must not hide the defeat burst");
|
||||
assertTrue(a.particleCalls.stream().anyMatch(call -> java.util.Arrays.asList(call).contains(defeatLocation)));
|
||||
@@ -116,7 +116,7 @@ class FantasyHealthNativeTest {
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.OUT_OF_WORLD)));
|
||||
var death = new org.bukkit.event.entity.PlayerDeathEvent(defeated.player, source,
|
||||
new java.util.ArrayList<>(), 0, net.kyori.adventure.text.Component.empty(), true);
|
||||
f.dispatcher.accept(death); awaitTail(f, defeated);
|
||||
f.dispatcher.accept(death); DownedSessionNativeTest.acceptDeath(f,defeated); awaitTail(f, defeated);
|
||||
assertTrue(death.isCancelled());
|
||||
assertEquals(0, receivedDust(defeated, org.bukkit.Color.RED));
|
||||
assertEquals(1, receivedDust(viewer, org.bukkit.Color.RED));
|
||||
@@ -331,7 +331,7 @@ class FantasyHealthNativeTest {
|
||||
assertEquals(44, a.player.getHealthScale()); assertTrue(a.player.isHealthScaled());
|
||||
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
|
||||
var saved = new games.dmg.fantasystick.persistence.YamlCharacterRepository(data.resolve("lifecycle-" + quit)).load(a.core.record.id()).orElseThrow();
|
||||
assertFalse(saved.dead()); assertEquals(0, saved.health().compareTo(java.math.BigDecimal.valueOf(4))); assertEquals(0, a.core.teleports);
|
||||
assertFalse(saved.dead());assertEquals(0,saved.health().compareTo(java.math.BigDecimal.valueOf(4)),"quit="+quit+", health="+saved.health());assertEquals(0,a.core.teleports,"quit="+quit);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,8 @@ class FantasyStickLifecycleNativeTest {
|
||||
assertTrue(fixture.order.indexOf("CharacterChatNames") >= 0);
|
||||
assertTrue(fixture.order.indexOf("CharacterChatNames") < recipe);
|
||||
assertNotNull(fixture.packetListener);
|
||||
assertEquals(18, fixture.timers.size(),
|
||||
"Presentation, ability/bond/rally/banner cleanup, provenance, reward retry, recovery, passive effects, armor/rare/adventure/fishing/dungeon refresh and session particles");
|
||||
assertEquals(19, fixture.timers.size(),
|
||||
"Presentation, ability/bond/rally/banner cleanup, provenance, reward retry, recovery, passive effects, armor/rare/adventure/fishing/dungeon/downed refresh and session particles");
|
||||
assertTrue(fixture.order.indexOf("PartyCombat") >= 0);
|
||||
assertTrue(fixture.order.indexOf("PartyCombat") < recipe);
|
||||
assertTrue(fixture.order.indexOf("CombatExperience") >= 0);
|
||||
@@ -393,7 +393,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void packagedDeathRegistrationAndReentrantDisableKeepAlreadyOwnedCharacterSave() throws Exception {
|
||||
@Test void packagedDowningRegistrationAndReentrantDisableRetainDurableCountdown() throws Exception {
|
||||
for (boolean disable : new boolean[]{false, true}) {
|
||||
var directory = data.resolve("death-" + disable);
|
||||
try (var f = new Fixture(directory)) {
|
||||
@@ -412,30 +412,32 @@ class FantasyStickLifecycleNativeTest {
|
||||
});
|
||||
assertTrue(entered.await(5, java.util.concurrent.TimeUnit.SECONDS));
|
||||
var sheet = a.core.inventory.getItemInOffHand().clone();
|
||||
if (disable) a.core.mutation = () -> { a.core.mutation = () -> {}; f.plugin.setEnabled(false); };
|
||||
if(disable)a.core.mutation=()->{};
|
||||
var source = new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.OUT_OF_WORLD)));
|
||||
var death = new org.bukkit.event.entity.PlayerDeathEvent(a.player, source, new ArrayList<>(), 7,
|
||||
net.kyori.adventure.text.Component.text("ordinary death"), true);
|
||||
try {
|
||||
f.dispatcher.accept(death);
|
||||
if(disable&&f.plugin.isEnabled())f.plugin.setEnabled(false);
|
||||
if(!disable)DownedSessionNativeTest.acceptDeath(f,a);
|
||||
assertTrue(death.isCancelled()); assertFalse(death.getKeepInventory());
|
||||
assertRestored(f, a, viewer);
|
||||
assertEquals(a.core.normalMaximum, a.core.health);
|
||||
assertEquals(org.bukkit.Material.DIAMOND_SWORD, a.core.inventory.getItem(0).getType());
|
||||
if(!disable)assertRestored(f,a,viewer);
|
||||
assertEquals(disable?20:a.core.normalMaximum,a.core.health,"disable="+disable+", messages="+a.messages);
|
||||
if(!disable)assertEquals(org.bukkit.Material.DIAMOND_SWORD,a.core.inventory.getItem(0).getType());
|
||||
assertEquals(sheet, a.core.inventory.getItemInOffHand());
|
||||
if (disable) assertFalse(sessions.drained().toCompletableFuture().isDone());
|
||||
// Downing skips an ordinary character-health save, so shutdown may already be drained.
|
||||
} finally { release.countDown(); }
|
||||
gate.get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
if (!disable) {
|
||||
f.tick(); assertEquals(org.bukkit.Material.WRITTEN_BOOK, a.core.inventory.getItemInOffHand().getType());
|
||||
f.tick();DownedSessionNativeTest.awaitTail(f,a);
|
||||
assertTrue(a.messages.stream().anyMatch(message -> message.startsWith("§c")), "Red defeat feedback port");
|
||||
f.plugin.setEnabled(false);
|
||||
}
|
||||
f.awaitWorkers(); sessions.drained().toCompletableFuture().get(5, java.util.concurrent.TimeUnit.SECONDS);
|
||||
assertTrue(new YamlCharacterRepository(directory).load(a.core.record.id()).orElseThrow().dead());
|
||||
assertEquals(1, a.core.teleports);
|
||||
if (disable) assertEquals(sheet, a.core.inventory.getItemInOffHand(), "No replacement on shutdown");
|
||||
assertEquals(!disable,new YamlCharacterRepository(directory).load(a.core.record.id()).orElseThrow().dead());
|
||||
assertEquals(disable?0:1, a.core.teleports);
|
||||
if (disable){assertEquals(sheet,a.core.inventory.getItemInOffHand(),"No replacement on shutdown");var retained=new games.dmg.fantasystick.session.DownedDirectory(directory,java.time.Clock.systemUTC());try{assertEquals(games.dmg.fantasystick.session.DownedEpisode.Phase.PENDING,retained.find(a.core.record.id()).join().orElseThrow().phase());}finally{retained.close();}}
|
||||
assertFalse(java.util.Arrays.stream(org.bukkit.event.entity.PlayerDeathEvent.getHandlerList().getRegisteredListeners())
|
||||
.anyMatch(listener -> listener.getPlugin() == f.plugin));
|
||||
}
|
||||
@@ -820,7 +822,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.GENERIC)));
|
||||
var death = new org.bukkit.event.entity.PlayerDeathEvent(a.player, source, new ArrayList<>(), 0,
|
||||
net.kyori.adventure.text.Component.empty(), true);
|
||||
f.dispatcher.accept(death); assertTrue(death.isCancelled());
|
||||
f.dispatcher.accept(death); DownedSessionNativeTest.acceptDeath(f,a); assertTrue(death.isCancelled());
|
||||
}
|
||||
default -> throw new AssertionError(route);
|
||||
}
|
||||
@@ -1403,6 +1405,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
final net.minecraft.world.food.FoodData food = new net.minecraft.world.food.FoodData();
|
||||
boolean healthScaled;
|
||||
boolean sprinting;
|
||||
boolean gravity=true;
|
||||
boolean allowed = true;
|
||||
boolean visible = true;
|
||||
String accountName = "Account";
|
||||
@@ -1472,6 +1475,11 @@ class FantasyStickLifecycleNativeTest {
|
||||
case "isSneaking", "isInvisible", "isDead" -> false;
|
||||
case "isSprinting" -> sprinting;
|
||||
case "setSprinting" -> { sprinting = (Boolean) args[0]; yield null; }
|
||||
case "hasGravity" -> gravity;
|
||||
case "setGravity" -> {gravity=(Boolean)args[0];yield null;}
|
||||
case "setVelocity","setFallDistance" -> null;
|
||||
case "isInsideVehicle" -> false;
|
||||
case "leaveVehicle" -> true;
|
||||
case "getScoreboard" -> craftBoard;
|
||||
case "sendMessage" -> {
|
||||
if (args[0] instanceof net.kyori.adventure.text.Component component) {
|
||||
@@ -1516,6 +1524,7 @@ class FantasyStickLifecycleNativeTest {
|
||||
var level = mock(net.minecraft.server.level.ServerLevel.class);
|
||||
when(nativePlayer.level()).thenReturn(level);
|
||||
when(world.getHandle()).thenReturn(level);
|
||||
when(world.getUID()).thenReturn(java.util.UUID.randomUUID());
|
||||
when(level.dimension()).thenReturn(net.minecraft.world.level.Level.OVERWORLD);
|
||||
var worldConfig = mock(io.papermc.paper.configuration.WorldConfiguration.class);
|
||||
worldConfig.entities = allocate(io.papermc.paper.configuration.WorldConfiguration.Entities.class);
|
||||
|
||||
@@ -71,7 +71,7 @@ class NutritionNativeTest {
|
||||
org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.OUT_OF_WORLD)));
|
||||
var death = new org.bukkit.event.entity.PlayerDeathEvent(a.player, source, new java.util.ArrayList<>(), 0,
|
||||
net.kyori.adventure.text.Component.empty(), true);
|
||||
f.dispatcher.accept(death); PartyBookNativeTest.drain(f);
|
||||
f.dispatcher.accept(death); DownedSessionNativeTest.acceptDeath(f,a); PartyBookNativeTest.drain(f);
|
||||
assertTrue(death.isCancelled());
|
||||
assertEquals(7, a.player.getFoodLevel()); assertEquals(2, a.player.getSaturation());
|
||||
assertEquals(3, a.player.getExhaustion());
|
||||
|
||||
@@ -28,18 +28,18 @@ class RareShopNativeTest {
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test void registeredMerchantPurchaseInventoryUseAndNativeHealingUseConnectedPath()throws Exception{
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-price-variance-percent: 0\nrare-price-health-potion: 40\nrare-stock-health-potion-min: 1\nrare-stock-health-potion-max: 1\nrare-price-reskill: 20\nrare-stock-reskill-min: 1\nrare-stock-reskill-max: 1\n");
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-price-variance-percent: 0\nrare-price-health-potion: 40\nrare-stock-health-potion-min: 1\nrare-stock-health-potion-max: 1\nrare-price-reskill: 20\nrare-stock-reskill-min: 2\nrare-stock-reskill-max: 2\nrare-price-magic-core: 30\nrare-stock-magic-core-min: 1\nrare-stock-magic-core-max: 1\n");
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){
|
||||
f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);doReturn(true).when(actor.player).hasPermission("fantasystick.admin");UUID worldId=UUID.randomUUID();when(actor.world.getUID()).thenReturn(worldId);int x=actor.core.location.getBlockX()>>4,z=actor.core.location.getBlockZ()>>4;var chunk=mock(Chunk.class);when(chunk.getWorld()).thenReturn(actor.world);when(chunk.getX()).thenReturn(x);when(chunk.getZ()).thenReturn(z);when(chunk.getEntities()).thenReturn(new org.bukkit.entity.Entity[0]);when(actor.world.getChunkAt(x,z)).thenReturn(chunk);when(actor.world.isChunkLoaded(x,z)).thenReturn(true);when(actor.world.getEntities()).thenReturn(List.of());
|
||||
assertEquals(List.of("list","place","remove","restock"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"rare-shop",""}));assertTrue(f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-"}).containsAll(List.of("rare-price-health-potion","rare-price-reskill","rare-stock-reskill-min","rare-stock-reskill-max")));assertEquals(List.of("20","2000"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-price-reskill",""}));
|
||||
assertEquals(List.of("list","place","remove","restock"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"rare-shop",""}));assertTrue(f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-"}).containsAll(List.of("rare-price-health-potion","rare-price-reskill","rare-stock-reskill-min","rare-stock-reskill-max","rare-price-magic-core","rare-stock-magic-core-min","rare-stock-magic-core-max")));assertEquals(List.of("20","2000"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-price-reskill",""}));assertEquals(List.of("30","3000"),f.command.tabComplete(actor.player,"fantasystick",new String[]{"config","rare-price-magic-core",""}));
|
||||
var villager=mock(Villager.class);when(villager.getLocation()).thenReturn(actor.core.location);var values=new HashMap<String,String>();var pdc=mock(PersistentDataContainer.class);when(villager.getPersistentDataContainer()).thenReturn(pdc);doAnswer(call->{values.put(((NamespacedKey)call.getArgument(0)).getKey(),call.getArgument(2));return null;}).when(pdc).set(any(NamespacedKey.class),eq(PersistentDataType.STRING),anyString());when(pdc.get(any(NamespacedKey.class),eq(PersistentDataType.STRING))).thenAnswer(call->values.get(((NamespacedKey)call.getArgument(0)).getKey()));doAnswer(call->{((java.util.function.Consumer<Villager>)call.getArgument(2)).accept(villager);return villager;}).when(actor.world).spawn(any(Location.class),eq(Villager.class),any(java.util.function.Consumer.class));
|
||||
f.command.execute(actor.player,"fantasystick",new String[]{"rare-shop","place","Curios"});await(f,()->((RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants")).all().size()==1);var directory=(RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants");var shop=directory.all().getFirst();assertEquals("Curios",shop.name());var controller=(RareMerchantController)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchantController");assertTrue(controller.tagged(villager));
|
||||
var repository=new YamlCharacterRepository(data);var old=repository.load(actor.core.record.id()).orElseThrow();var purchasedStats=new java.util.EnumMap<>(old.stats());purchasedStats.put(games.dmg.fantasystick.progression.Stat.DEX,BigInteger.ONE);repository.replace(new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),purchasedStats,old.level(),old.experience(),BigInteger.valueOf(39),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,BigInteger.valueOf(100),true,old.rewardReceipts(),old.pvpCoinEscrow(),old.gear()),old.revision());f.activate(actor);
|
||||
var repository=new YamlCharacterRepository(data);var old=repository.load(actor.core.record.id()).orElseThrow();var purchasedStats=new java.util.EnumMap<>(old.stats());purchasedStats.put(games.dmg.fantasystick.progression.Stat.DEX,BigInteger.ONE);repository.replace(new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),purchasedStats,old.level(),old.experience(),BigInteger.valueOf(39),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,BigInteger.valueOf(150),true,old.rewardReceipts(),old.pvpCoinEscrow(),old.gear()),old.revision());f.activate(actor);
|
||||
int opened=actor.inventories.size(),books=actor.books.size();var main=new PlayerInteractEntityEvent(actor.player,villager,EquipmentSlot.HAND);var offhand=new PlayerInteractEntityEvent(actor.player,villager,EquipmentSlot.OFF_HAND);f.dispatcher.accept(main);f.dispatcher.accept(offhand);assertTrue(main.isCancelled());assertTrue(offhand.isCancelled());await(f,()->actor.inventories.size()==opened+1);assertEquals(books,actor.books.size());var menu=actor.inventories.getLast();var potion=menu.getItem(11);assertEquals(Material.POTION,potion.getType());assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(potion.getItemMeta().displayName()).contains("Health Potion — 40 coins"));assertEquals("Stock: 1",net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(potion.getItemMeta().lore().getFirst()));
|
||||
var menus=(RareShopMenus)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareShopMenus");var click=mock(InventoryClickEvent.class);when(click.getInventory()).thenReturn(menu);when(click.getWhoClicked()).thenReturn(actor.player);when(click.getCurrentItem()).thenReturn(potion);menus.click(click);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION).equals(BigInteger.ONE));var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");await(f,()->sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(60))).orElse(false));var active=sessions.active(actor.core.id).orElseThrow(()->new AssertionError("Purchase removed active session: "+actor.messages));var record=sessions.currentRecord(active).orElseThrow(()->new AssertionError("Purchase left no current record: "+actor.messages));var injured=characters.saveHealth(record.id(),record.revision(),BigDecimal.valueOf(5),BigDecimal.valueOf(100)).join().orElseThrow(()->new AssertionError("Injury save was refused"));assertTrue(sessions.acknowledgeProgress(active,record.revision(),injured));actor.player.setHealth(5);
|
||||
var menus=(RareShopMenus)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareShopMenus");var click=mock(InventoryClickEvent.class);when(click.getInventory()).thenReturn(menu);when(click.getWhoClicked()).thenReturn(actor.player);when(click.getCurrentItem()).thenReturn(potion);menus.click(click);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION).equals(BigInteger.ONE));var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");await(f,()->sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(110))).orElse(false));var active=sessions.active(actor.core.id).orElseThrow(()->new AssertionError("Purchase removed active session: "+actor.messages));var record=sessions.currentRecord(active).orElseThrow(()->new AssertionError("Purchase left no current record: "+actor.messages));var injured=characters.saveHealth(record.id(),record.revision(),BigDecimal.valueOf(5),BigDecimal.valueOf(100)).join().orElseThrow(()->new AssertionError("Injury save was refused"));assertTrue(sessions.acknowledgeProgress(active,record.revision(),injured));actor.player.setHealth(5);
|
||||
PartyBookNativeTest.open(f,actor);assertTrue(PartyBookNativeTest.text(actor).contains("Health Potion"),PartyBookNativeTest.text(actor));assertTrue(PartyBookNativeTest.text(actor).contains("[Use]"),PartyBookNativeTest.text(actor));var action=PartyBookNativeTest.button(actor,"[Use]");PartyBookNativeTest.click(f,actor,action);await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION).signum()==0&&actor.player.getHealth()>5&&actor.messages.stream().anyMatch(message->message.contains("Used Health Potion")));assertEquals(10d,actor.player.getHealth());assertEquals(0,BigDecimal.TEN.compareTo(characters.find(record.id()).join().orElseThrow().health()));assertTrue(actor.messages.stream().anyMatch(message->message.contains("Used Health Potion")&&message.contains("restored")));
|
||||
int menusBeforeReskill=actor.inventories.size();menus.open(actor.player,shop.id());await(f,()->actor.inventories.size()>menusBeforeReskill);var reskillMenu=actor.inventories.getLast();var reskill=reskillMenu.getItem(13);assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(reskill.getItemMeta().displayName()).contains("Reskill — 20 coins"));var reskillClick=mock(InventoryClickEvent.class);when(reskillClick.getInventory()).thenReturn(reskillMenu);when(reskillClick.getWhoClicked()).thenReturn(actor.player);when(reskillClick.getCurrentItem()).thenReturn(reskill);menus.click(reskillClick);await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).equals(BigInteger.ONE));await(f,()->sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(40))&&!value.stats().get(games.dmg.fantasystick.progression.Stat.DEX).equals(BigInteger.ZERO)).orElse(false));PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->PartyBookNativeTest.text(actor).contains("Confirm Reskill"));PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Confirm Reskill]"));await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).signum()==0&&sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.stats().values().stream().allMatch(BigInteger.ZERO::equals)&&value.unspentPoints().equals(BigInteger.valueOf(40))).orElse(false));var resetActive=sessions.active(actor.core.id).orElseThrow();var resetRecord=sessions.currentRecord(resetActive).orElseThrow();var repurchased=characters.purchaseStat(resetRecord.id(),resetRecord.revision(),games.dmg.fantasystick.progression.Stat.DEX,BigDecimal.valueOf(actor.player.getHealth()),new BigDecimal("1024")).join().record().orElseThrow();assertTrue(sessions.acknowledgeProgress(resetActive,resetRecord.revision(),repurchased));assertEquals(BigInteger.ONE,repurchased.stats().get(games.dmg.fantasystick.progression.Stat.DEX));assertEquals(BigInteger.valueOf(39),repurchased.unspentPoints());
|
||||
f.plugin.setEnabled(false);f.awaitWorkers();f.plugin.setEnabled(true);var reloaded=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION));assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.RESKILL));assertEquals(BigInteger.ONE,new YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow().stats().get(games.dmg.fantasystick.progression.Stat.DEX));assertTrue(((RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants")).find(shop.id()).isPresent());
|
||||
int menusBeforeReskill=actor.inventories.size();menus.open(actor.player,shop.id());await(f,()->actor.inventories.size()>menusBeforeReskill);var reskillMenu=actor.inventories.getLast();var reskill=reskillMenu.getItem(13);assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(reskill.getItemMeta().displayName()).contains("Reskill — 20 coins"));var reskillClick=mock(InventoryClickEvent.class);when(reskillClick.getInventory()).thenReturn(reskillMenu);when(reskillClick.getWhoClicked()).thenReturn(actor.player);when(reskillClick.getCurrentItem()).thenReturn(reskill);menus.click(reskillClick);await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).equals(BigInteger.ONE));await(f,()->sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(90))&&!value.stats().get(games.dmg.fantasystick.progression.Stat.DEX).equals(BigInteger.ZERO)).orElse(false));PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->PartyBookNativeTest.text(actor).contains("Confirm Reskill"));PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Confirm Reskill]"));await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).signum()==0&&sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.stats().values().stream().allMatch(BigInteger.ZERO::equals)&&value.unspentPoints().equals(BigInteger.valueOf(40))).orElse(false));var resetActive=sessions.active(actor.core.id).orElseThrow();var resetRecord=sessions.currentRecord(resetActive).orElseThrow();var repurchased=characters.purchaseStat(resetRecord.id(),resetRecord.revision(),games.dmg.fantasystick.progression.Stat.DEX,BigDecimal.valueOf(actor.player.getHealth()),new BigDecimal("1024")).join().record().orElseThrow();assertTrue(sessions.acknowledgeProgress(resetActive,resetRecord.revision(),repurchased));assertEquals(BigInteger.ONE,repurchased.stats().get(games.dmg.fantasystick.progression.Stat.DEX));assertEquals(BigInteger.valueOf(39),repurchased.unspentPoints());int beforeCoreMenu=actor.inventories.size();menus.open(actor.player,shop.id());await(f,()->actor.inventories.size()>beforeCoreMenu);var coreMenu=actor.inventories.getLast();var coreItem=coreMenu.getItem(14);assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(coreItem.getItemMeta().displayName()).contains("Magic Core — 30 coins"));var coreClick=mock(InventoryClickEvent.class);when(coreClick.getInventory()).thenReturn(coreMenu);when(coreClick.getWhoClicked()).thenReturn(actor.player);when(coreClick.getCurrentItem()).thenReturn(coreItem);menus.click(coreClick);awaitEvidence(f,()->inventory.quantity(actor.core.record.id(),RareProduct.MAGIC_CORE).equals(BigInteger.ONE)&&sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(60))).orElse(false),()->"core purchase inventory="+inventory.inventory(actor.core.record.id())+" record="+sessions.active(actor.core.id).flatMap(sessions::currentRecord)+" messages="+actor.messages);PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));awaitEvidence(f,()->inventory.quantity(actor.core.record.id(),RareProduct.MAGIC_CORE).signum()==0&&sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.unspentPoints().equals(BigInteger.valueOf(40))).orElse(false),()->"core use inventory="+inventory.inventory(actor.core.record.id())+" record="+sessions.active(actor.core.id).flatMap(sessions::currentRecord)+" messages="+actor.messages);int beforeSecondReskill=actor.inventories.size();menus.open(actor.player,shop.id());await(f,()->actor.inventories.size()>beforeSecondReskill);var secondReskillMenu=actor.inventories.getLast();var secondReskill=secondReskillMenu.getItem(13);var secondReskillClick=mock(InventoryClickEvent.class);when(secondReskillClick.getInventory()).thenReturn(secondReskillMenu);when(secondReskillClick.getWhoClicked()).thenReturn(actor.player);when(secondReskillClick.getCurrentItem()).thenReturn(secondReskill);menus.click(secondReskillClick);awaitEvidence(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).equals(BigInteger.ONE)&&sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(value->value.coins().equals(BigInteger.valueOf(40))).orElse(false),()->"second reskill inventory="+inventory.inventory(actor.core.record.id())+" messages="+actor.messages);PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->PartyBookNativeTest.text(actor).contains("Confirm Reskill"));PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Confirm Reskill]"));awaitEvidence(f,()->inventory.quantity(actor.core.record.id(),RareProduct.RESKILL).signum()==0&&sessions.active(aLine truncated
|
||||
f.plugin.setEnabled(false);f.awaitWorkers();f.plugin.setEnabled(true);var reloaded=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.HEALTH_POTION));assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.RESKILL));assertEquals(BigInteger.ZERO,reloaded.quantity(actor.core.record.id(),RareProduct.MAGIC_CORE));var persisted=new YamlCharacterRepository(data).load(actor.core.record.id()).orElseThrow();assertTrue(persisted.stats().values().stream().allMatch(BigInteger.ZERO::equals));assertEquals(BigInteger.valueOf(41),persisted.unspentPoints());assertTrue(((RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants")).find(shop.id()).isPresent());
|
||||
}
|
||||
}
|
||||
@Test void reskillUseRequiresFreshConfirmationThenResetsTheExactActiveCharacter()throws Exception{
|
||||
@@ -53,6 +53,10 @@ class RareShopNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void magicCoreUseAddsOneVisibleSpendableOrdinaryPoint()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");inventory.add(actor.core.record.id(),RareProduct.MAGIC_CORE,UUID.randomUUID()).join();PartyBookNativeTest.open(f,actor);String before=PartyBookNativeTest.text(actor);assertTrue(before.contains("Magic Core: 1"),before);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");await(f,()->inventory.quantity(actor.core.record.id(),RareProduct.MAGIC_CORE).signum()==0&&sessions.active(actor.core.id).flatMap(sessions::currentRecord).map(record->record.unspentPoints().equals(BigInteger.valueOf(41))).orElse(false));var active=sessions.active(actor.core.id).orElseThrow();var record=sessions.currentRecord(active).orElseThrow();var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var spent=characters.purchaseStat(record.id(),record.revision(),games.dmg.fantasystick.progression.Stat.STR,BigDecimal.valueOf(actor.player.getHealth()),new BigDecimal("1024")).join().record().orElseThrow();assertTrue(sessions.acknowledgeProgress(active,record.revision(),spent));assertEquals(BigInteger.ONE,spent.stats().get(games.dmg.fantasystick.progression.Stat.STR));assertEquals(BigInteger.valueOf(40),spent.unspentPoints());}
|
||||
}
|
||||
|
||||
@Test void reskillWithNothingInvestedRefusesWithoutConsumingTheStoredItem()throws Exception{
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");inventory.add(actor.core.record.id(),RareProduct.RESKILL,UUID.randomUUID()).join();PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->actor.messages.stream().anyMatch(message->message.contains("no investments")));assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.RESKILL));assertFalse(PartyBookNativeTest.text(actor).contains("Confirm Reskill"));}
|
||||
}
|
||||
@@ -61,13 +65,13 @@ class RareShopNativeTest {
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);var repository=new YamlCharacterRepository(data);var old=repository.load(actor.core.record.id()).orElseThrow();var stats=new java.util.EnumMap<>(old.stats());stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);var invested=new CharacterRecord(old.id(),old.name(),old.revision().add(BigInteger.ONE),stats,old.level(),old.experience(),BigInteger.valueOf(39),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,old.coins(),old.coinsInitialized(),old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());repository.replace(invested,old.revision());f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");inventory.add(invested.id(),RareProduct.RESKILL,UUID.randomUUID()).join();PartyBookNativeTest.open(f,actor);PartyBookNativeTest.click(f,actor,PartyBookNativeTest.button(actor,"[Use]"));await(f,()->PartyBookNativeTest.text(actor).contains("Confirm Reskill"));var confirm=PartyBookNativeTest.button(actor,"[Confirm Reskill]");var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");var active=sessions.active(actor.core.id).orElseThrow();var current=sessions.currentRecord(active).orElseThrow();var progressed=characters.awardCombatReward(current.id(),current.revision(),UUID.randomUUID(),BigInteger.ONE,BigInteger.ZERO,games.dmg.fantasystick.progression.ProgressionRules.defaults(),games.dmg.fantasystick.progression.CombatRewardRules.defaults(),null).join().record().orElseThrow();assertTrue(sessions.acknowledgeProgress(active,current.revision(),progressed));PartyBookNativeTest.click(f,actor,confirm);await(f,()->actor.messages.stream().anyMatch(message->message.contains("build or quantity changed")));assertEquals(BigInteger.ONE,inventory.quantity(invested.id(),RareProduct.RESKILL));var retained=sessions.currentRecord(active).orElseThrow();assertEquals(BigInteger.ONE,retained.stats().get(games.dmg.fantasystick.progression.Stat.STR));assertEquals(BigInteger.ONE,retained.experience());}
|
||||
}
|
||||
|
||||
@Test void restartConsumesOnlyReskillsWithAuthoritativeResetProofAndRefundsUnappliedReservations()throws Exception{
|
||||
var factory=new games.dmg.fantasystick.crafting.CharacterFactory();var base=factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var other=factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var stats=new java.util.EnumMap<>(base.stats());stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);var invested=new CharacterRecord(base.id(),base.name(),base.revision(),stats,base.level(),base.experience(),BigInteger.valueOf(39),base.health(),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,base.coins(),base.coinsInitialized(),base.rewardReceipts(),base.pvpCoinEscrow(),base.gear(),base.sheetGeneration());var repository=new YamlCharacterRepository(data);repository.create(invested);repository.create(other);UUID applied=UUID.randomUUID(),unapplied=UUID.randomUUID();
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var characters=new CharacterStorage(repository,java.time.Clock.systemUTC())){inventory.add(invested.id(),RareProduct.RESKILL,UUID.randomUUID()).join();inventory.add(other.id(),RareProduct.RESKILL,UUID.randomUUID()).join();inventory.reserveUse(invested.id(),RareProduct.RESKILL,applied,BigInteger.ONE).join();inventory.reserveUse(other.id(),RareProduct.RESKILL,unapplied,BigInteger.ONE).join();assertEquals(CharacterStorage.ReskillStatus.APPLIED,characters.reskill(invested.id(),invested.revision(),applied,new BigDecimal("1024")).join().status());}
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");await(f,()->inventory.unresolvedUses().isEmpty());assertEquals(BigInteger.ZERO,inventory.quantity(invested.id(),RareProduct.RESKILL));assertEquals(BigInteger.ONE,inventory.quantity(other.id(),RareProduct.RESKILL));var saved=new YamlCharacterRepository(data).load(invested.id()).orElseThrow();assertEquals(BigInteger.valueOf(40),saved.unspentPoints());assertTrue(saved.stats().values().stream().allMatch(BigInteger.ZERO::equals));}
|
||||
@Test void restartReconcilesReskillAndMagicCoreReservationsFromAuthoritativeCharacterProof()throws Exception{
|
||||
var factory=new games.dmg.fantasystick.crafting.CharacterFactory();var base=factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var other=factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var stats=new java.util.EnumMap<>(base.stats());stats.put(games.dmg.fantasystick.progression.Stat.STR,BigInteger.ONE);var invested=new CharacterRecord(base.id(),base.name(),base.revision(),stats,base.level(),base.experience(),BigInteger.valueOf(39),base.health(),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,base.coins(),base.coinsInitialized(),base.rewardReceipts(),base.pvpCoinEscrow(),base.gear(),base.sheetGeneration());var repository=new YamlCharacterRepository(data);repository.create(invested);repository.create(other);UUID applied=UUID.randomUUID(),unapplied=UUID.randomUUID(),appliedCore=UUID.randomUUID(),unappliedCore=UUID.randomUUID();
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var characters=new CharacterStorage(repository,java.time.Clock.systemUTC())){inventory.add(invested.id(),RareProduct.RESKILL,UUID.randomUUID()).join();inventory.add(other.id(),RareProduct.RESKILL,UUID.randomUUID()).join();inventory.add(invested.id(),RareProduct.MAGIC_CORE,UUID.randomUUID()).join();inventory.add(other.id(),RareProduct.MAGIC_CORE,UUID.randomUUID()).join();inventory.reserveUse(invested.id(),RareProduct.RESKILL,applied,BigInteger.ONE).join();inventory.reserveUse(other.id(),RareProduct.RESKILL,unapplied,BigInteger.ONE).join();inventory.reserveUse(invested.id(),RareProduct.MAGIC_CORE,appliedCore,BigInteger.ONE).join();inventory.reserveUse(other.id(),RareProduct.MAGIC_CORE,unappliedCore,BigInteger.ONE).join();var reset=characters.reskill(invested.id(),invested.revision(),applied,new BigDecimal("1024")).join().record().orElseThrow();assertEquals(CharacterStorage.MagicCoreStatus.APPLIED,characters.consumeMagicCore(reset.id(),reset.revision(),appliedCore).join().status());}
|
||||
try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");await(f,()->inventory.unresolvedUses().isEmpty());assertEquals(BigInteger.ZERO,inventory.quantity(invested.id(),RareProduct.RESKILL));assertEquals(BigInteger.ONE,inventory.quantity(other.id(),RareProduct.RESKILL));assertEquals(BigInteger.ZERO,inventory.quantity(invested.id(),RareProduct.MAGIC_CORE));assertEquals(BigInteger.ONE,inventory.quantity(other.id(),RareProduct.MAGIC_CORE));var saved=new YamlCharacterRepository(data).load(invested.id()).orElseThrow();assertEquals(BigInteger.valueOf(41),saved.unspentPoints());assertTrue(saved.stats().values().stream().allMatch(BigInteger.ZERO::equals));}
|
||||
}
|
||||
|
||||
@Test void everyMerchantSharesOneAllZeroCatalogAndShowsAnEmptyShop()throws Exception{java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-stock-lesser-health-potion-min: 0\nrare-stock-lesser-health-potion-max: 0\nrare-stock-health-potion-min: 0\nrare-stock-health-potion-max: 0\nrare-stock-greater-health-potion-min: 0\nrare-stock-greater-health-potion-max: 0\nrare-stock-reskill-min: 0\nrare-stock-reskill-max: 0\n");try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);UUID world=UUID.randomUUID();when(actor.world.getUID()).thenReturn(world);f.activate(actor);var directory=(RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants");var first=directory.place("One",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var second=directory.place("Two",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var menus=(RareShopMenus)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareShopMenus");menus.open(actor.player,first.id());await(f,()->!actor.inventories.isEmpty());var one=actor.inventories.getLast();assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(13).getItemMeta().displayName()).contains("Reskill"));assertEquals(Material.BARRIER,one.getItem(16).getType());menus.open(actor.player,second.id());await(f,()->actor.inventories.size()>=2);var two=actor.inventories.getLast();assertEquals(one.getItem(10).getItemMeta().displayName(),two.getItem(10).getItemMeta().displayName());assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(10).getItemMeta().displayName()).startsWith("Sold out"));}}
|
||||
@Test void everyMerchantSharesOneAllZeroCatalogAndShowsAnEmptyShop()throws Exception{java.nio.file.Files.writeString(data.resolve("config.yml"),"rare-stock-lesser-health-potion-min: 0\nrare-stock-lesser-health-potion-max: 0\nrare-stock-health-potion-min: 0\nrare-stock-health-potion-max: 0\nrare-stock-greater-health-potion-min: 0\nrare-stock-greater-health-potion-max: 0\nrare-stock-reskill-min: 0\nrare-stock-reskill-max: 0\nrare-stock-magic-core-min: 0\nrare-stock-magic-core-max: 0\n");try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);UUID world=UUID.randomUUID();when(actor.world.getUID()).thenReturn(world);f.activate(actor);var directory=(RareMerchantDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareMerchants");var first=directory.place("One",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var second=directory.place("Two",world,actor.core.location.getX(),actor.core.location.getY(),actor.core.location.getZ(),0,0).join();var menus=(RareShopMenus)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareShopMenus");menus.open(actor.player,first.id());await(f,()->!actor.inventories.isEmpty());var one=actor.inventories.getLast();assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(13).getItemMeta().displayName()).contains("Reskill"));assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(14).getItemMeta().displayName()).contains("Magic Core"));assertEquals(Material.BARRIER,one.getItem(16).getType());menus.open(actor.player,second.id());await(f,()->actor.inventories.size()>=2);var two=actor.inventories.getLast();assertEquals(one.getItem(10).getItemMeta().displayName(),two.getItem(10).getItemMeta().displayName());assertTrue(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer.plainText().serialize(one.getItem(10).getItemMeta().displayName()).startsWith("Sold out"));}}
|
||||
|
||||
@Test void allPotionSizesPreserveFractionalHealingAndFullHealthStock()throws Exception{try(var f=new FantasyStickLifecycleNativeTest.Fixture(data)){f.plugin.setEnabled(true);var actor=new FantasyStickLifecycleNativeTest.Actor(data);f.players.put(actor.core.id,actor.player);f.activate(actor);var inventory=(RareInventoryDirectory)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareInventory");var characters=(CharacterStorage)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"characters");var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"sessions");inventory.add(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION,UUID.randomUUID()).join();injure(actor,characters,sessions,new BigDecimal("4"));useFirst(f,actor);awaitEvidence(f,()->actor.player.getHealth()==6.5&&inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION).signum()==0,()->"lesser health="+actor.player.getHealth()+" quantity="+inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION)+" messages="+actor.messages);inventory.add(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION,UUID.randomUUID()).join();injure(actor,characters,sessions,BigDecimal.TEN);var potionService=(RarePotionService)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rarePotions");var refusal=new java.util.concurrent.atomic.AtomicReference<RarePotionService.Outcome>();potionService.use(actor.player,RareProduct.LESSER_HEALTH_POTION,refusal::set);assertEquals(RarePotionService.Status.FULL_HEALTH,refusal.get().status());assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION));var settings=(RareSettings)FantasyStickLifecycleNativeTest.Fixture.field(f.plugin,"rareSettings");var zero=settings.set("rare-lesser-health-potion-healing-percent","0").toCompletableFuture().join();assertTrue(settings.publish(zero));injure(actor,characters,sessions,BigDecimal.ONE);var noEffect=new java.util.concurrent.atomic.AtomicReference<RarePotionService.Outcome>();potionService.use(actor.player,RareProduct.LESSER_HEALTH_POTION,noEffect::set);assertEquals(RarePotionService.Status.NO_EFFECT,noEffect.get().status());assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION));inventory.add(actor.core.record.id(),RareProduct.GREATER_HEALTH_POTION,UUID.randomUUID()).join();injure(actor,characters,sessions,BigDecimal.ONE);var greater=new java.util.concurrent.atomic.AtomicReference<RarePotionService.Outcome>();potionService.use(actor.player,RareProduct.GREATER_HEALTH_POTION,greater::set);awaitEvidence(f,()->greater.get()!=null&&greater.get().status()==RarePotionService.Status.APPLIED&&actor.player.getHealth()==10&&inventory.quantity(actor.core.record.id(),RareProduct.GREATER_HEALTH_POTION).signum()==0,()->"greater outcome="+greater.get()+" health="+actor.player.getHealth()+" quantities="+inventory.inventory(actor.core.record.id())+" messages="+actor.messages);assertEquals(BigInteger.ONE,inventory.quantity(actor.core.record.id(),RareProduct.LESSER_HEALTH_POTION));}}
|
||||
private static void injure(FantasyStickLifecycleNativeTest.Actor actor,CharacterStorage characters,games.dmg.fantasystick.session.EquipmentSessions sessions,BigDecimal health){var active=sessions.active(actor.core.id).orElseThrow();var record=sessions.currentRecord(active).orElseThrow();var saved=characters.saveHealth(record.id(),record.revision(),health,BigDecimal.valueOf(100)).join().orElseThrow();if(!saved.revision().equals(record.revision()))assertTrue(sessions.acknowledgeProgress(active,record.revision(),saved));actor.player.setHealth(health.doubleValue());}
|
||||
|
||||
@@ -47,6 +47,10 @@ class ReviveNativeTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void learnedAimedReviveRestoresAnyPartyDownedCharacterInPlace()throws Exception{
|
||||
try(var fixture=new FantasyStickLifecycleNativeTest.Fixture(data)){fixture.plugin.setEnabled(true);var caster=new FantasyStickLifecycleNativeTest.Actor(data);withRevive(data,caster);var target=new FantasyStickLifecycleNativeTest.Actor(data);fixture.players.put(caster.core.id,caster.player);fixture.players.put(target.core.id,target.player);var worldId=java.util.UUID.randomUUID();org.mockito.Mockito.when(caster.world.getUID()).thenReturn(worldId);org.mockito.Mockito.when(target.world.getUID()).thenReturn(worldId);fixture.activate(caster);fixture.activate(target);caster.core.location.setWorld(caster.world);caster.core.location.setX(0);caster.core.location.setY(64);caster.core.location.setZ(0);target.core.location.setWorld(caster.world);target.core.location.setX(3);target.core.location.setY(64);target.core.location.setZ(0);var anchor=target.core.location.clone();org.mockito.Mockito.doReturn(true).when(caster.player).hasLineOfSight(target.player);target.core.health=0;var source=new org.bukkit.craftbukkit.damage.CraftDamageSource(new net.minecraft.world.damagesource.DamageSource(org.bukkit.craftbukkit.damage.CraftDamageType.bukkitToMinecraftHolder(org.bukkit.damage.DamageType.GENERIC)));fixture.dispatcher.accept(new org.bukkit.event.entity.PlayerDeathEvent(target.player,source,new java.util.ArrayList<>(),0,net.kyori.adventure.text.Component.empty(),true));var downed=(games.dmg.fantasystick.session.DownedController)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"downedController");for(int attempt=0;attempt<80&&!downed.downed(target.player);attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}caster.core.inventory.getInventory().setSelectedSlot(2);fixture.dispatcher.accept(new org.bukkit.event.player.PlayerInteractEntityEvent(caster.player,target.player,org.bukkit.inventory.EquipmentSlot.HAND));for(int attempt=0;attempt<120&&downed.downed(target.player);attempt++){var task=fixture.tasks.poll(50,java.util.concurrent.TimeUnit.MILLISECONDS);if(task!=null)task.run();Thread.sleep(5);}var sessions=(games.dmg.fantasystick.session.EquipmentSessions)FantasyStickLifecycleNativeTest.Fixture.field(fixture.plugin,"sessions");assertFalse(downed.downed(target.player),()->"caster="+caster.messages+", target="+target.messages);assertTrue(sessions.current(sessions.active(target.core.id).orElseThrow()));assertEquals(target.maximumHealth.getValue(),target.player.getHealth());assertEquals(anchor,target.player.getLocation());assertNotEquals(org.bukkit.Material.WRITTEN_BOOK,target.core.inventory.getItemInOffHand().getType());var casterRecord=sessions.currentRecord(sessions.active(caster.core.id).orElseThrow()).orElseThrow();assertTrue(casterRecord.cooldowns().get("revive").isAfter(java.time.Instant.now().plusSeconds(86300)));}
|
||||
}
|
||||
|
||||
@Test void ordinaryTargetSelectsOneTailAndReceivesTheSameLivingSheetOnce() throws Exception {
|
||||
try (var fixture = new FantasyStickLifecycleNativeTest.Fixture(data)) {
|
||||
fixture.plugin.setEnabled(true);
|
||||
|
||||
@@ -78,7 +78,7 @@ class DistributionTest {
|
||||
"adventure-champion-reward-xp: 150", "adventure-champion-reward-coins: 40")) {
|
||||
assertTrue(defaults.contains(setting), "Missing packaged adventure default: " + setting);
|
||||
}
|
||||
for(String setting:java.util.List.of("rare-price-reskill: 2000","rare-stock-reskill-min: 0","rare-stock-reskill-max: 1"))assertTrue(defaults.contains(setting),"Missing packaged Reskill default: "+setting);
|
||||
for(String setting:java.util.List.of("rare-price-reskill: 2000","rare-stock-reskill-min: 0","rare-stock-reskill-max: 1","rare-price-magic-core: 3000","rare-stock-magic-core-min: 0","rare-stock-magic-core-max: 3"))assertTrue(defaults.contains(setting),"Missing packaged Reskill default: "+setting);
|
||||
assertFalse(defaults.contains("rare-reskill-healing-percent"));
|
||||
assertTrue(defaults.contains("great-sword-base-damage: 7"));
|
||||
assertTrue(defaults.contains("great-sword-recovery-seconds: 0.75"));
|
||||
|
||||
@@ -371,6 +371,18 @@ class CharacterStorageTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void magicCoreAddsExactlyOneArbitraryPrecisionOrdinaryPointWithoutChangingMaxLevelOrXp()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var huge=BigInteger.TEN.pow(100);var maxed=new CharacterRecord(base.id(),base.name(),base.revision(),base.stats(),30,BigInteger.valueOf(29000),huge,base.health(),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,base.coins(),base.coinsInitialized(),base.rewardReceipts(),base.pvpCoinEscrow(),base.gear(),base.sheetGeneration());repository.create(maxed);UUID operation=UUID.randomUUID();try(var storage=new CharacterStorage(repository,Clock.systemUTC())){var credited=storage.consumeMagicCore(maxed.id(),maxed.revision(),operation).join();assertEquals(CharacterStorage.MagicCoreStatus.APPLIED,credited.status());var saved=credited.record().orElseThrow();assertEquals(huge.add(BigInteger.ONE),saved.unspentPoints());assertEquals(30,saved.level());assertEquals(BigInteger.valueOf(29000),saved.experience());assertEquals(CharacterStorage.MagicCoreStatus.DUPLICATE,storage.consumeMagicCore(maxed.id(),maxed.revision(),operation).join().status());var second=storage.consumeMagicCore(saved.id(),saved.revision(),UUID.randomUUID()).join().record().orElseThrow();assertEquals(huge.add(BigInteger.TWO),second.unspentPoints());assertEquals(saved.level(),second.level());assertEquals(saved.experience(),second.experience());assertEquals(second,repository.load(saved.id()).orElseThrow());}
|
||||
}
|
||||
|
||||
@Test void failedMagicCoreCreditLeavesTheCharacterRetryableWithoutAFreePoint()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());repository.create(base);var failing=new YamlCharacterRepository(data,(source,target)->{throw new IOException("simulated Core credit failure");});UUID operation=UUID.randomUUID();try(var storage=new CharacterStorage(failing,Clock.systemUTC())){assertThrows(CompletionException.class,()->storage.consumeMagicCore(base.id(),base.revision(),operation).join());}assertEquals(base,repository.load(base.id()).orElseThrow());try(var storage=new CharacterStorage(repository,Clock.systemUTC())){var saved=storage.consumeMagicCore(base.id(),base.revision(),operation).join().record().orElseThrow();assertEquals(base.unspentPoints().add(BigInteger.ONE),saved.unspentPoints());}
|
||||
}
|
||||
|
||||
@Test void magicCoreGainSurvivesActualStatSpendingAndReskillRefund()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());repository.create(base);try(var storage=new CharacterStorage(repository,Clock.systemUTC())){var first=storage.consumeMagicCore(base.id(),base.revision(),UUID.randomUUID()).join().record().orElseThrow();var second=storage.consumeMagicCore(first.id(),first.revision(),UUID.randomUUID()).join().record().orElseThrow();var credited=storage.consumeMagicCore(second.id(),second.revision(),UUID.randomUUID()).join().record().orElseThrow();var stat=storage.purchaseStat(credited.id(),credited.revision(),games.dmg.fantasystick.progression.Stat.STR,credited.health(),new java.math.BigDecimal("1024")).join().record().orElseThrow();var ability=storage.unlockAbility(stat.id(),stat.revision(),"core_ability",java.util.Map.of(),BigInteger.ONE).join().record().orElseThrow();var passive=storage.unlockPassive(ability.id(),ability.revision(),"core_passive",java.util.Map.of(),java.util.Set.of(),BigInteger.ONE).join().record().orElseThrow();assertEquals(BigInteger.valueOf(40),passive.unspentPoints());assertEquals(BigInteger.ONE,passive.stats().get(games.dmg.fantasystick.progression.Stat.STR));assertTrue(passive.learned().contains("core_ability"));assertTrue(passive.passives().contains("core_passive"));var reset=storage.reskill(passive.id(),passive.revision(),UUID.randomUUID(),new java.math.BigDecimal("1024")).join().record().orElseThrow();assertEquals(BigInteger.valueOf(43),reset.unspentPoints());assertTrue(reset.stats().values().stream().allMatch(BigInteger.ZERO::equals));assertTrue(reset.learned().isEmpty());assertTrue(reset.passives().stream().allMatch(String::isEmpty));}
|
||||
}
|
||||
|
||||
@Test void reskillPreservesLowerPositiveHealthAndNoOpDoesNotWriteAReceipt()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var stats=new java.util.EnumMap<>(base.stats());stats.put(games.dmg.fantasystick.progression.Stat.CON,BigInteger.valueOf(5));var invested=new CharacterRecord(base.id(),base.name(),base.revision(),stats,base.level(),base.experience(),BigInteger.valueOf(35),new java.math.BigDecimal("4.25"),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,base.coins(),base.coinsInitialized(),base.rewardReceipts(),base.pvpCoinEscrow(),base.gear(),base.sheetGeneration());repository.create(invested);try(var storage=new CharacterStorage(repository,Clock.systemUTC())){var applied=storage.reskill(invested.id(),invested.revision(),UUID.randomUUID(),new java.math.BigDecimal("1024")).join().record().orElseThrow();assertEquals(new java.math.BigDecimal("4.25"),applied.health());assertEquals(BigInteger.valueOf(40),applied.unspentPoints());var operation=UUID.randomUUID();var noOp=storage.reskill(applied.id(),applied.revision(),operation,new java.math.BigDecimal("1024")).join();assertEquals(CharacterStorage.ReskillStatus.NOTHING_TO_RESET,noOp.status());assertEquals(applied,noOp.record().orElseThrow());assertFalse(applied.rewardReceipts().contains(operation));assertEquals(applied,repository.load(applied.id()).orElseThrow());}
|
||||
}
|
||||
@@ -526,6 +538,10 @@ class CharacterStorageTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void downedFinalDeathUsesCapturedResolutionTimeAndStableIdentityExactlyOnce()throws Exception{
|
||||
var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());repository.create(base);UUID death=UUID.randomUUID();var expiry=java.time.Instant.parse("2026-09-24T02:05:00Z");try(var storage=new CharacterStorage(repository,Clock.systemUTC())){var first=storage.recordFinalDeath(base.id(),base.revision(),death,expiry,true).join().orElseThrow();assertTrue(first.dead());assertEquals(death,first.deathId());assertEquals(expiry,first.diedAt());assertEquals(BigInteger.ZERO,first.coins());assertEquals(base.coins(),first.pvpCoinEscrow());var duplicate=storage.recordFinalDeath(base.id(),base.revision(),death,expiry,true).join().orElseThrow();assertEquals(first,duplicate);assertTrue(storage.recordFinalDeath(base.id(),base.revision(),UUID.randomUUID(),expiry.plusSeconds(1),true).join().isEmpty());}
|
||||
}
|
||||
|
||||
@Test
|
||||
void failedRevivalSaveLeavesDeadStateRetryableAndShutdownRejectsNewWork() throws Exception {
|
||||
var saved = YamlCharacterRepositoryTest.sample(UUID.randomUUID());
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package games.dmg.fantasystick.persistence;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class DownedSettingsTest{
|
||||
@TempDir Path data;
|
||||
@Test void validatesAndPublishesDurableDownedPoliciesWithoutRewritingUnrelatedConfiguration()throws Exception{
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),"unrelated: keep\n");
|
||||
try(var settings=new DownedSettings(data,Map.of())){
|
||||
assertEquals(Duration.ofSeconds(300),settings.timeout());assertEquals(Duration.ofSeconds(5),settings.protection());
|
||||
assertThrows(IllegalArgumentException.class,()->settings.set(DownedSettings.TIMEOUT,"0"));
|
||||
assertThrows(IllegalArgumentException.class,()->settings.set(DownedSettings.PROTECTION,"31536001"));
|
||||
var zero=settings.set(DownedSettings.PROTECTION,"0").toCompletableFuture().join();assertEquals(Duration.ofSeconds(5),settings.protection());assertTrue(settings.publish(zero));assertEquals(Duration.ZERO,settings.protection());
|
||||
}
|
||||
assertTrue(java.nio.file.Files.readString(data.resolve("config.yml")).contains("unrelated: keep"));
|
||||
}
|
||||
}
|
||||
@@ -94,6 +94,20 @@ class EquipmentSessionStoreTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void downedResumeReopensOnlyTheExactCompletedSession()throws Exception{
|
||||
try(var store=new EquipmentSessionStore(data,CLOCK)){
|
||||
await(store.prepare(player,session,character,"SURVIVAL"));
|
||||
await(store.completeExit(player,session,Duration.ZERO));
|
||||
failure(store.resume(player,UUID.randomUUID(),character,"SURVIVAL",null));
|
||||
failure(store.resume(player,session,UUID.randomUUID(),"SURVIVAL",null));
|
||||
var resumed=await(store.resume(player,session,character,"SURVIVAL",null));
|
||||
assertEquals(session,resumed.pending().sessionId());
|
||||
assertEquals(character,resumed.pending().characterId());
|
||||
failure(store.resume(player,session,character,"SURVIVAL",null));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void atomicExitFailureKeepsReceiptAndExistingDeadlineUntilSingleWriteRetry() throws Exception {
|
||||
EquipmentSessionStore.State exited;
|
||||
|
||||
@@ -22,6 +22,15 @@ class RareSettingsTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test void registersMagicCoreForTheNextSharedCatalogWithoutAnEffectMultiplier()throws Exception{
|
||||
try(var settings=new RareSettings(data,Map.of())){
|
||||
assertTrue(RareSettings.keys().containsAll(java.util.List.of("rare-price-magic-core","rare-stock-magic-core-min","rare-stock-magic-core-max")));
|
||||
assertFalse(RareSettings.keys().stream().anyMatch(key->key.contains("magic-core")&&key.contains("point")));
|
||||
assertEquals("3000",settings.value("rare-price-magic-core"));assertEquals("0",settings.value("rare-stock-magic-core-min"));assertEquals("3",settings.value("rare-stock-magic-core-max"));
|
||||
assertEquals(java.math.BigInteger.valueOf(3000),settings.rules().basePrices().get(RareProduct.MAGIC_CORE));assertFalse(settings.rules().healingPercent().containsKey(RareProduct.MAGIC_CORE));
|
||||
}
|
||||
}
|
||||
|
||||
@Test void validatesRangesAndPublishesOnlyAcknowledgedWritesWhilePreservingOtherYaml()throws Exception{
|
||||
java.nio.file.Files.writeString(data.resolve("config.yml"),"unrelated: keep\n");
|
||||
try(var settings=new RareSettings(data,Map.of())){
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package games.dmg.fantasystick.session;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.UUID;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class DownedDirectoryTest {
|
||||
@TempDir java.nio.file.Path data;
|
||||
|
||||
@Test void capturesOneDurableEpisodeDeadlineAndExactlyOneOutcomeAcrossRestart()throws Exception{
|
||||
var now=new java.util.concurrent.atomic.AtomicReference<>(Instant.parse("2026-09-24T01:00:00Z"));
|
||||
var clock=new Clock(){public java.time.ZoneId getZone(){return ZoneOffset.UTC;}public Clock withZone(java.time.ZoneId zone){return this;}public Instant instant(){return now.get();}};
|
||||
UUID character=UUID.randomUUID(),player=UUID.randomUUID(),session=UUID.randomUUID(),world=UUID.randomUUID();
|
||||
DownedEpisode episode;
|
||||
try(var directory=new DownedDirectory(data,clock)){
|
||||
episode=directory.begin(character,player,session,world,1.25,64,-3.5,90,10,world,20,80,30,45,5,Duration.ofSeconds(300),new DownedEpisode.Attribution(UUID.randomUUID(),"PROJECTILE",true)).join();
|
||||
assertEquals(Instant.parse("2026-09-24T01:05:00Z"),episode.expiresAt());
|
||||
assertEquals(DownedEpisode.Phase.PENDING,episode.phase());
|
||||
assertEquals(episode,directory.find(character).join().orElseThrow());
|
||||
}
|
||||
now.set(Instant.parse("2026-09-24T01:04:59Z"));
|
||||
try(var directory=new DownedDirectory(data,clock)){
|
||||
assertEquals(episode,directory.find(character).join().orElseThrow());
|
||||
assertEquals(20,episode.entryX());
|
||||
assertEquals(80,episode.entryY());
|
||||
assertTrue(directory.find(character).join().orElseThrow().attribution().playerDefeat());
|
||||
var operation=UUID.randomUUID();var revived=directory.claim(episode.id(),DownedEpisode.Outcome.REVIVED,operation,Duration.ofSeconds(5)).join();
|
||||
assertEquals(DownedDirectory.ClaimStatus.APPLIED,revived.status());
|
||||
assertEquals(DownedEpisode.Phase.RESOLVED,revived.episode().orElseThrow().phase());
|
||||
assertEquals(DownedEpisode.Outcome.REVIVED,revived.episode().orElseThrow().outcome());
|
||||
assertEquals(Instant.parse("2026-09-24T01:05:04Z"),revived.episode().orElseThrow().protectionUntil());
|
||||
assertFalse(revived.episode().orElseThrow().published());
|
||||
assertThrows(java.util.concurrent.CompletionException.class,()->directory.publish(episode.id(),UUID.randomUUID()).join());
|
||||
assertTrue(directory.publish(episode.id(),operation).join().published());
|
||||
assertEquals(DownedDirectory.ClaimStatus.ALREADY_RESOLVED,directory.claim(episode.id(),DownedEpisode.Outcome.FINAL_DEATH,UUID.randomUUID(),Duration.ZERO).join().status());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void concurrentRescueAndDeathClaimsPublishExactlyOneDurableWinner()throws Exception{
|
||||
var clock=Clock.fixed(Instant.parse("2026-09-24T01:30:00Z"),ZoneOffset.UTC);
|
||||
try(var directory=new DownedDirectory(data,clock)){
|
||||
var episode=directory.begin(UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),0,64,0,0,0,Duration.ofMinutes(5),new DownedEpisode.Attribution(null,"ENVIRONMENT")).join();
|
||||
var revive=directory.claim(episode.id(),DownedEpisode.Outcome.REVIVED,UUID.randomUUID(),Duration.ofSeconds(5));
|
||||
var death=directory.claim(episode.id(),DownedEpisode.Outcome.FINAL_DEATH,UUID.randomUUID(),Duration.ZERO);
|
||||
var statuses=java.util.List.of(revive.join().status(),death.join().status());
|
||||
assertEquals(1,statuses.stream().filter(DownedDirectory.ClaimStatus.APPLIED::equals).count());
|
||||
assertEquals(1,statuses.stream().filter(DownedDirectory.ClaimStatus.ALREADY_RESOLVED::equals).count());
|
||||
var winner=directory.find(episode.character()).join().orElseThrow();
|
||||
assertEquals(DownedEpisode.Phase.RESOLVED,winner.phase());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void expiryRejectsRescueAndUsesTheOriginalDeadlineAsFinalDeathTime()throws Exception{
|
||||
var now=new java.util.concurrent.atomic.AtomicReference<>(Instant.parse("2026-09-24T02:00:00Z"));
|
||||
var clock=new Clock(){public java.time.ZoneId getZone(){return ZoneOffset.UTC;}public Clock withZone(java.time.ZoneId zone){return this;}public Instant instant(){return now.get();}};
|
||||
try(var directory=new DownedDirectory(data,clock)){
|
||||
var episode=directory.begin(UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),UUID.randomUUID(),0,70,0,0,0,Duration.ofSeconds(300),new DownedEpisode.Attribution(null,"ENVIRONMENT")).join();
|
||||
now.set(episode.expiresAt());
|
||||
assertEquals(DownedDirectory.ClaimStatus.EXPIRED,directory.claim(episode.id(),DownedEpisode.Outcome.REVIVED,UUID.randomUUID(),Duration.ofSeconds(5)).join().status());
|
||||
var recipient=UUID.randomUUID();var frozen=java.util.List.of(new DownedEpisode.Reward(recipient,java.math.BigInteger.TEN,java.math.BigInteger.valueOf(7)));var death=directory.claim(episode.id(),DownedEpisode.Outcome.FINAL_DEATH,UUID.randomUUID(),Duration.ZERO,frozen).join();
|
||||
assertEquals(DownedDirectory.ClaimStatus.APPLIED,death.status());
|
||||
assertEquals(episode.expiresAt(),death.episode().orElseThrow().resolvedAt());
|
||||
assertEquals(episode.attribution(),death.episode().orElseThrow().attribution());
|
||||
assertEquals(frozen,death.episode().orElseThrow().finalRewards());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@ class RareInventoryDirectoryTest {
|
||||
@Test void nonHealingUseReservationRetainsTypedRecoveryProofAcrossRestart()throws Exception{
|
||||
UUID character=UUID.randomUUID(),purchase=UUID.randomUUID(),use=UUID.randomUUID();
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){
|
||||
inventory.add(character,RareProduct.RESKILL,purchase).join();inventory.add(character,RareProduct.RESKILL,UUID.randomUUID()).join();inventory.add(character,RareProduct.HEALTH_POTION,UUID.randomUUID()).join();
|
||||
inventory.add(character,RareProduct.RESKILL,purchase).join();inventory.add(character,RareProduct.RESKILL,UUID.randomUUID()).join();inventory.add(character,RareProduct.HEALTH_POTION,UUID.randomUUID()).join();inventory.add(character,RareProduct.MAGIC_CORE,UUID.randomUUID()).join();
|
||||
var reservation=inventory.reserveUse(character,RareProduct.RESKILL,use,BigInteger.TWO).join();
|
||||
assertEquals(RareInventoryDirectory.UseStatus.RESERVED,reservation.status());
|
||||
assertNull(reservation.use().healthBefore());assertNull(reservation.use().maximum());assertEquals(0,reservation.use().percent());
|
||||
@@ -54,7 +54,7 @@ class RareInventoryDirectoryTest {
|
||||
try(var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){
|
||||
var proof=inventory.unresolvedUses().getFirst();assertEquals(use,proof.operation());assertEquals(RareProduct.RESKILL.id(),proof.product());
|
||||
assertEquals(RareInventoryDirectory.UseStatus.COMMITTED,inventory.commitUse(use).join());
|
||||
assertEquals(BigInteger.ONE,inventory.quantity(character,RareProduct.RESKILL));assertEquals(BigInteger.ONE,inventory.quantity(character,RareProduct.HEALTH_POTION));
|
||||
assertEquals(BigInteger.ONE,inventory.quantity(character,RareProduct.RESKILL));assertEquals(BigInteger.ONE,inventory.quantity(character,RareProduct.HEALTH_POTION));assertEquals(BigInteger.ONE,inventory.quantity(character,RareProduct.MAGIC_CORE));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,15 +28,19 @@ class RareMarketTest {
|
||||
try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(character).join();var catalog=market.current().toCompletableFuture().join();var bought=market.purchase(character.id(),character.revision(),catalog.revision(),RareProduct.RESKILL).toCompletableFuture().join();assertEquals(RareMarket.PurchaseStatus.APPLIED,bought.status());var saved=bought.record().orElseThrow();assertEquals(stats,saved.stats());assertEquals(character.learned(),saved.learned());assertEquals(character.cooldowns(),saved.cooldowns());assertEquals(BigInteger.valueOf(1000),saved.coins());assertEquals(BigInteger.ONE,inventory.quantity(character.id(),RareProduct.RESKILL));}finally{settings.close();}
|
||||
}
|
||||
|
||||
@Test void buyingMagicCoreStoresItWithoutGrantingAPoint()throws Exception{
|
||||
var clock=Clock.fixed(Instant.parse("2026-09-24T12:00:00Z"),ZoneOffset.UTC);var settings=new RareSettings(data,Map.of("rare-price-variance-percent","0","rare-price-magic-core","3000","rare-stock-magic-core-min","1","rare-stock-magic-core-max","1"));var repository=new YamlCharacterRepository(data);var base=new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults());var character=new CharacterRecord(base.id(),base.name(),base.revision(),base.stats(),base.level(),base.experience(),base.unspentPoints(),base.health(),base.learned(),base.loadout(),base.passives(),base.cooldowns(),base.restrictedKills(),false,null,null,BigInteger.valueOf(4000),true,Set.of(),BigInteger.ZERO,CharacterGear.none());try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(character).join();var catalog=market.current().toCompletableFuture().join();var bought=market.purchase(character.id(),character.revision(),catalog.revision(),RareProduct.MAGIC_CORE).toCompletableFuture().join();assertEquals(RareMarket.PurchaseStatus.APPLIED,bought.status());assertEquals(character.unspentPoints(),bought.record().orElseThrow().unspentPoints());assertEquals(BigInteger.valueOf(1000),bought.record().orElseThrow().coins());assertEquals(BigInteger.ONE,inventory.quantity(character.id(),RareProduct.MAGIC_CORE));}finally{settings.close();}
|
||||
}
|
||||
|
||||
@Test void restartFinishesDebitInventoryAndStockAfterSettlementFailureWithoutDuplication()throws Exception{var clock=Clock.fixed(Instant.parse("2026-09-23T12:00:00Z"),ZoneOffset.UTC);var settings=new RareSettings(data,Map.of("rare-price-variance-percent","0","rare-price-health-potion","40","rare-stock-health-potion-min","1","rare-stock-health-potion-max","1"));var charactersRepository=new YamlCharacterRepository(data);var character=withCoins(new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));var durable=new YamlRareCatalogRepository(data);class Failing implements RareCatalogRepository{int saves;public java.util.Optional<RareCatalog> load()throws java.io.IOException{return durable.load();}public void save(RareCatalog catalog)throws java.io.IOException{if(++saves==3)throw new java.io.IOException("injected settlement failure");durable.save(catalog);}}try(var characters=new CharacterStorage(charactersRepository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data))){characters.create(character).join();try(var market=new RareMarket(new Failing(),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){var catalog=market.current().toCompletableFuture().join();assertThrows(java.util.concurrent.CompletionException.class,()->market.purchase(character.id(),character.revision(),catalog.revision(),RareProduct.HEALTH_POTION).toCompletableFuture().join());}}try(var characters=new CharacterStorage(charactersRepository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(durable,new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->maximum)){var catalog=market.current().toCompletableFuture().join();assertEquals(BigInteger.valueOf(60),characters.find(character.id()).join().orElseThrow().coins());assertEquals(BigInteger.ONE,inventory.quantity(character.id(),RareProduct.HEALTH_POTION));assertEquals(0,catalog.offer(RareProduct.HEALTH_POTION).remaining());assertTrue(catalog.transactions().isEmpty());}finally{settings.close();}}
|
||||
|
||||
@Test void competingBuyersCannotOversellTheLastSharedUnit()throws Exception{var clock=Clock.fixed(Instant.parse("2026-09-23T12:00:00Z"),ZoneOffset.UTC);var settings=new RareSettings(data,Map.of("rare-price-variance-percent","0","rare-price-health-potion","40","rare-stock-health-potion-min","1","rare-stock-health-potion-max","1"));var repository=new YamlCharacterRepository(data);var factory=new games.dmg.fantasystick.crafting.CharacterFactory();var a=withCoins(factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));var b=withCoins(factory.create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(a).join();characters.create(b).join();var catalog=market.current().toCompletableFuture().join();var first=market.purchase(a.id(),a.revision(),catalog.revision(),RareProduct.HEALTH_POTION).toCompletableFuture();var second=market.purchase(b.id(),b.revision(),catalog.revision(),RareProduct.HEALTH_POTION).toCompletableFuture();assertEquals(java.util.Set.of(RareMarket.PurchaseStatus.APPLIED,RareMarket.PurchaseStatus.SOLD_OUT),java.util.Set.of(first.join().status(),second.join().status()));assertEquals(0,market.current().toCompletableFuture().join().offer(RareProduct.HEALTH_POTION).remaining());assertEquals(BigInteger.ONE,inventory.quantity(a.id(),RareProduct.HEALTH_POTION).add(inventory.quantity(b.id(),RareProduct.HEALTH_POTION)));}finally{settings.close();}}
|
||||
|
||||
private static CharacterRecord withCoins(CharacterRecord old){return new CharacterRecord(old.id(),old.name(),old.revision(),old.stats(),old.level(),old.experience(),old.unspentPoints(),old.health(),old.learned(),old.loadout(),old.passives(),old.cooldowns(),old.restrictedKills(),false,null,null,BigInteger.valueOf(100),true,java.util.Set.of(),BigInteger.ZERO,CharacterGear.none());}
|
||||
|
||||
@Test void newlyDeliveredReskillWaitsForTheNextRefreshInsteadOfRerollingTheCurrentCatalog()throws Exception{
|
||||
var now=Instant.parse("2026-09-24T12:00:00Z");var clock=Clock.fixed(now,ZoneOffset.UTC);var offers=new java.util.EnumMap<RareProduct,RareCatalog.Offer>(RareProduct.class);for(var product:List.of(RareProduct.LESSER_HEALTH_POTION,RareProduct.HEALTH_POTION,RareProduct.GREATER_HEALTH_POTION))offers.put(product,new RareCatalog.Offer(BigInteger.ONE,1));var revision=java.util.UUID.randomUUID();var legacy=new RareCatalog(LocalDate.of(2026,9,24),revision,now,RareCatalog.RefreshReason.STARTUP,offers);new YamlRareCatalogRepository(data).save(legacy);var settings=new RareSettings(data,Map.of("rare-stock-reskill-min","1","rare-stock-reskill-max","1"));var repository=new YamlCharacterRepository(data);var character=withCoins(new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));
|
||||
try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(character).join();var current=market.current().toCompletableFuture().join();assertEquals(revision,current.revision());assertFalse(current.available(RareProduct.RESKILL));assertEquals(RareMarket.PurchaseStatus.UNAVAILABLE,market.purchase(character.id(),character.revision(),revision,RareProduct.RESKILL).toCompletableFuture().join().status());var refreshed=market.restock().toCompletableFuture().join();assertTrue(refreshed.available(RareProduct.RESKILL));assertEquals(1,refreshed.offer(RareProduct.RESKILL).remaining());}finally{settings.close();}
|
||||
@Test void newlyDeliveredProductsWaitForTheNextRefreshInsteadOfRerollingTheCurrentCatalog()throws Exception{
|
||||
var now=Instant.parse("2026-09-24T12:00:00Z");var clock=Clock.fixed(now,ZoneOffset.UTC);var offers=new java.util.EnumMap<RareProduct,RareCatalog.Offer>(RareProduct.class);for(var product:List.of(RareProduct.LESSER_HEALTH_POTION,RareProduct.HEALTH_POTION,RareProduct.GREATER_HEALTH_POTION))offers.put(product,new RareCatalog.Offer(BigInteger.ONE,1));var revision=java.util.UUID.randomUUID();var legacy=new RareCatalog(LocalDate.of(2026,9,24),revision,now,RareCatalog.RefreshReason.STARTUP,offers);new YamlRareCatalogRepository(data).save(legacy);var settings=new RareSettings(data,Map.of("rare-stock-reskill-min","1","rare-stock-reskill-max","1","rare-stock-magic-core-min","1","rare-stock-magic-core-max","1"));var repository=new YamlCharacterRepository(data);var character=withCoins(new games.dmg.fantasystick.crafting.CharacterFactory().create(games.dmg.fantasystick.progression.ProgressionRules.defaults()));
|
||||
try(var characters=new CharacterStorage(repository,clock);var inventory=new RareInventoryDirectory(new YamlRareInventoryRepository(data));var market=new RareMarket(new YamlRareCatalogRepository(data),new RarePurchaseOperationStore(data),characters,inventory,settings::rules,clock,(minimum,maximum)->minimum)){characters.create(character).join();var current=market.current().toCompletableFuture().join();assertEquals(revision,current.revision());assertFalse(current.available(RareProduct.RESKILL));assertFalse(current.available(RareProduct.MAGIC_CORE));assertEquals(RareMarket.PurchaseStatus.UNAVAILABLE,market.purchase(character.id(),character.revision(),revision,RareProduct.MAGIC_CORE).toCompletableFuture().join().status());var refreshed=market.restock().toCompletableFuture().join();assertTrue(refreshed.available(RareProduct.RESKILL));assertTrue(refreshed.available(RareProduct.MAGIC_CORE));assertEquals(1,refreshed.offer(RareProduct.RESKILL).remaining());assertEquals(1,refreshed.offer(RareProduct.MAGIC_CORE).remaining());}finally{settings.close();}
|
||||
}
|
||||
|
||||
@Test void staleGenerationAndZeroStockRefuseWithoutCoinsOrInventoryMutation() throws Exception {
|
||||
|
||||
Reference in new issue
Block a user