using PkmnLib.Dynamic.Libraries;
using PkmnLib.Dynamic.Models;
using PkmnLib.Dynamic.ScriptHandling;
using PkmnLib.Plugin.Gen7.Libraries.Battling;
using PkmnLib.Plugin.Gen7.Scripts.Items.Pokeballs;
using PkmnLib.Static;
using PkmnLib.Static.Species;
namespace PkmnLib.Plugin.Gen7.Tests.Scripts.Items.Pokeballs;
///
/// Tests for the item script.
/// Bulbapedia: "When used from the Bag in a wild encounter, it catches the wild Pokémon without fail (with some
/// exceptions mentioned below). Despite the common misconception that the Master Ball has a low chance to fail in
/// certain generations, it functions by simply overriding the catch formula entirely, skipping any calculations
/// based on chance."
///
public class MasterBallTests
{
///
/// Looks up a real item from the loaded Gen7 library.
///
private static IItem GetItem(IDynamicLibrary library, string name)
{
if (!library.StaticLibrary.Items.TryGet(name, out var item))
throw new InvalidOperationException($"Failed to load item {name}.");
return item;
}
///
/// Creates a real level 50 Pokémon of the given species from the loaded Gen7 library.
///
private static IPokemon CreatePokemon(IDynamicLibrary library, string speciesName)
{
if (!library.StaticLibrary.Species.TryGet(speciesName, out var species))
throw new InvalidOperationException($"Failed to load species {speciesName}.");
return new PokemonImpl(library, species, species.GetDefaultForm(), new AbilityIndex
{
Index = 0,
IsHidden = false,
}, 50, 0, Gender.Genderless, 0, "hardy");
}
///
/// Creates a mocked wild Pokémon at full health with the given species catch rate. The default is 3, the lowest
/// catch rate in the games. is the real Gen7 library, so thrown items resolve to
/// their real scripts.
///
private static IBattlePokemon CreateFullHealthTarget(IDynamicLibrary library, byte captureRate = 3)
{
var species = Substitute.For();
species.CaptureRate.Returns(captureRate);
var target = Substitute.For();
target.Library.Returns(library);
target.Species.Returns(species);
target.BoostedStats.Returns(new StatisticSet(100, 0, 0, 0, 0, 0));
target.CurrentHealth.Returns(100u);
target.GetScripts().Returns(new ScriptIterator([]));
return target;
}
///
/// Creates a random source that always rolls the highest possible value, so every shake check of the regular
/// capture formula fails and a critical capture never triggers.
///
private static IBattleRandom CreateWorstRolls()
{
var random = Substitute.For();
random.GetInt(Arg.Any(), Arg.Any()).Returns(call => call.ArgAt(1) - 1);
return random;
}
///
/// Creates a random source that always rolls the lowest possible value, so every shake check of the regular
/// capture formula succeeds and a critical capture triggers whenever it is possible.
///
private static IBattleRandom CreateBestRolls()
{
var random = Substitute.For();
random.GetInt(Arg.Any(), Arg.Any()).Returns(0);
return random;
}
///
/// Bulbapedia: "it catches the wild Pokémon without fail". The script reports a perfect capture rate to the
/// capture library through .
///
[Test]
public async Task IsAlwaysSuccessful_AnyTarget_ReturnsTrue()
{
// Arrange
var masterBall = new MasterBall(Substitute.For());
var target = Substitute.For();
// Act
var result = masterBall.IsAlwaysSuccessful(target);
// Assert
await Assert.That(result).IsTrue();
}
///
/// Bulbapedia: "it functions by simply overriding the catch formula entirely". The Master Ball has no catch rate
/// multiplier of its own, so leaves the rate untouched.
///
[Test, Arguments((byte)0), Arguments((byte)3), Arguments((byte)45), Arguments((byte)255)]
public async Task ChangeCatchRate_AnyCatchRate_LeavesCatchRateUnchanged(byte initialCatchRate)
{
// Arrange
var masterBall = new MasterBall(Substitute.For());
var target = Substitute.For();
var catchRate = initialCatchRate;
// Act
masterBall.ChangeCatchRate(target, ref catchRate);
// Assert
await Assert.That(catchRate).IsEqualTo(initialCatchRate);
}
///
/// Bulbapedia: "When used from the Bag in a wild encounter, it catches the wild Pokémon". A Pokémon in a wild
/// battle is a valid target for .
///
[Test]
public async Task IsTargetValid_PokemonInWildBattle_ReturnsTrue()
{
// Arrange
var masterBall = new MasterBall(Substitute.For());
var battle = Substitute.For();
battle.IsWildBattle.Returns(true);
var target = Substitute.For();
target.Battle.Returns(battle);
// Act
var result = masterBall.IsTargetValid(target);
// Assert
await Assert.That(result).IsTrue();
}
///
/// Bulbapedia: "If used in a Trainer battle (except if used as a Snag Ball on a Shadow Pokémon), the opposing
/// Trainer will deflect it". A Pokémon in a trainer battle is not a valid target.
///
[Test]
public async Task IsTargetValid_PokemonInTrainerBattle_ReturnsFalse()
{
// Arrange
var masterBall = new MasterBall(Substitute.For());
var battle = Substitute.For();
battle.IsWildBattle.Returns(false);
var target = Substitute.For();
target.Battle.Returns(battle);
// Act
var result = masterBall.IsTargetValid(target);
// Assert
await Assert.That(result).IsFalse();
}
///
/// Bulbapedia: the Master Ball is used "in a wild encounter". A Pokémon that is not in a battle at all is not a
/// valid target.
///
[Test]
public async Task IsTargetValid_PokemonOutsideBattle_ReturnsFalse()
{
// Arrange
var masterBall = new MasterBall(Substitute.For());
var target = Substitute.For();
// Act
var result = masterBall.IsTargetValid(target);
// Assert
await Assert.That(result).IsFalse();
}
///
/// The master_ball item in the Gen7 data resolves to the script, so the capture
/// library picks up the guaranteed capture when the real item is thrown.
///
[Test]
public async Task ScriptResolver_MasterBallItem_ResolvesToMasterBallScript()
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var item = GetItem(library, "master_ball");
// Act
var resolved = library.ScriptResolver.TryResolveBattleItemScript(item, out var script);
// Assert
await Assert.That(resolved).IsTrue();
await Assert.That(script).IsTypeOf();
}
///
/// Bulbapedia: "it catches the wild Pokémon without fail". Even the hardest possible target, a catch rate 3
/// species at full health, with every shake check failing, is caught by .
///
[Test]
public async Task TryCapture_MasterBallOnHardestTargetWithWorstRolls_IsCaught()
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var captureLibrary = new Gen7CaptureLibrary(new Gen7PluginConfiguration());
var target = CreateFullHealthTarget(library);
// Act
var result = captureLibrary.TryCapture(target, GetItem(library, "master_ball"), CreateWorstRolls());
// Assert
await Assert.That(result.IsCaught).IsTrue();
}
///
/// Sanity check for the setup of :
/// under the same conditions an ordinary Poké Ball fails, so the guaranteed capture really comes from the
/// Master Ball and not from the test setup.
///
[Test]
public async Task TryCapture_PokeBallOnHardestTargetWithWorstRolls_IsNotCaught()
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var captureLibrary = new Gen7CaptureLibrary(new Gen7PluginConfiguration());
var target = CreateFullHealthTarget(library);
// Act
var result = captureLibrary.TryCapture(target, GetItem(library, "poke_ball"), CreateWorstRolls());
// Assert
await Assert.That(result.IsCaught).IsFalse();
}
///
/// Bulbapedia: "it functions by simply overriding the catch formula entirely, skipping any calculations based on
/// chance." No random number is rolled when a Master Ball is thrown.
///
[Test]
public async Task TryCapture_MasterBall_DoesNotRollRandom()
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var captureLibrary = new Gen7CaptureLibrary(new Gen7PluginConfiguration());
var target = CreateFullHealthTarget(library);
var random = CreateWorstRolls();
// Act
captureLibrary.TryCapture(target, GetItem(library, "master_ball"), random);
// Assert
await Assert.That(random.ReceivedCalls()).IsEmpty();
}
///
/// Bulbapedia: "skipping any calculations based on chance". The critical capture roll is part of the formula the
/// Master Ball skips, so a species caught hundreds of times still reports a regular capture through
/// , even with rolls that would otherwise guarantee a critical capture.
///
[Test]
public async Task TryCapture_MasterBallOnSpeciesCaughtManyTimesWithBestRolls_IsNotCriticalCapture()
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var captureLibrary = new Gen7CaptureLibrary(new Gen7PluginConfiguration
{
TimesSpeciesCaught = _ => 1000,
});
var target = CreateFullHealthTarget(library, 200);
// Act
var result = captureLibrary.TryCapture(target, GetItem(library, "master_ball"), CreateBestRolls());
// Assert
await Assert.That(result.IsCaught).IsTrue();
await Assert.That(result.CriticalCapture).IsFalse();
}
///
/// Sanity check for the setup of
/// : under the same
/// conditions an ordinary Poké Ball does trigger a critical capture, so the Master Ball really skips that roll.
///
[Test]
public async Task TryCapture_PokeBallOnSpeciesCaughtManyTimesWithBestRolls_IsCriticalCapture()
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var captureLibrary = new Gen7CaptureLibrary(new Gen7PluginConfiguration
{
TimesSpeciesCaught = _ => 1000,
});
var target = CreateFullHealthTarget(library, 200);
// Act
var result = captureLibrary.TryCapture(target, GetItem(library, "poke_ball"), CreateBestRolls());
// Assert
await Assert.That(result.CriticalCapture).IsTrue();
}
///
/// Bulbapedia (Catch rate): "If a Master Ball is used, the amount of successful shake checks is set to four."
/// A Master Ball capture therefore reports the full four shakes in , the same
/// as any other guaranteed capture.
///
[Test]
public async Task TryCapture_MasterBall_ReportsFourShakes()
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var captureLibrary = new Gen7CaptureLibrary(new Gen7PluginConfiguration());
var target = CreateFullHealthTarget(library);
// Act
var result = captureLibrary.TryCapture(target, GetItem(library, "master_ball"), CreateWorstRolls());
// Assert
await Assert.That(result.Shakes).IsEqualTo(4);
}
///
/// Bulbapedia: "it catches the wild Pokémon without fail". Using the real Master Ball item through
/// in a real wild battle against a full-health Beldum (catch rate 3)
/// captures it on the first attempt, whatever the battle's random seed is.
///
[Test, Arguments(0), Arguments(1), Arguments(7), Arguments(1234)]
public async Task OnUseWithTarget_RealWildBattle_CapturesTargetOnFirstAttempt(int seed)
{
// Arrange
var library = LibraryHelpers.LoadLibrary();
var own = CreatePokemon(library, "bulbasaur");
var wildPokemon = CreatePokemon(library, "beldum");
var party = new PokemonPartyImpl(1);
party.SwapInto(own, 0);
var wildParty = new PokemonPartyImpl(1);
wildParty.SwapInto(wildPokemon, 0);
using var battle = new BattleImpl(library, [
new BattlePartyImpl(party, [new ResponsibleIndex(0, 0)]),
new BattlePartyImpl(wildParty, [new ResponsibleIndex(1, 0)]),
], false, 2, 1, true, "grass", seed);
battle.Sides[0].SendOut(0, own);
battle.Sides[1].SendOut(0, wildPokemon);
var wildBattlePokemon = battle.GetPokemon(1, 0)!;
var masterBallItem = GetItem(library, "master_ball");
if (!library.ScriptResolver.TryResolveBattleItemScript(masterBallItem, out var masterBall))
throw new InvalidOperationException("Failed to resolve the master ball script.");
// Act
masterBall.OnUseWithTarget(wildBattlePokemon, battle.EventHook);
// Assert
await Assert.That(wildBattlePokemon.IsCaught).IsTrue();
await Assert.That(battle.Result!.Value.CapturedPokemon).Contains(wildPokemon);
}
}