Adds helper function to find what Pokemon evolves into what

This commit is contained in:
Deukhoofd 2024-09-30 14:59:39 +02:00
parent 38e6630c67
commit e7cda474f1
Signed by: Deukhoofd
GPG Key ID: F63E044490819F6F

View File

@ -13,6 +13,10 @@ public interface IReadOnlySpeciesLibrary : IEnumerable<ISpecies>
/// Tries to get a species from the library. Returns false if the species is not found. /// Tries to get a species from the library. Returns false if the species is not found.
/// </summary> /// </summary>
bool TryGet(StringKey key, [MaybeNullWhen(false)] out ISpecies value); bool TryGet(StringKey key, [MaybeNullWhen(false)] out ISpecies value);
/// <summary>
/// Tried to get a species from the library by its national dex number. Returns false if the species is not found.
/// </summary>
bool TryGetById(int id, [MaybeNullWhen(false)] out ISpecies value); bool TryGetById(int id, [MaybeNullWhen(false)] out ISpecies value);
/// <summary> /// <summary>
@ -29,11 +33,19 @@ public interface IReadOnlySpeciesLibrary : IEnumerable<ISpecies>
/// Whether the library is empty. /// Whether the library is empty.
/// </summary> /// </summary>
bool IsEmpty { get; } bool IsEmpty { get; }
/// <summary>
/// Finds the Pokémon that evolves into the given species. If the species does not evolve, returns null.
/// If multiple species evolve into the given species, returns the first one found.
/// </summary>
ISpecies? FindPreEvolution(ISpecies species);
} }
/// <inheritdoc cref="IReadOnlySpeciesLibrary"/> /// <inheritdoc cref="IReadOnlySpeciesLibrary"/>
public class SpeciesLibrary : DataLibrary<ISpecies>, IReadOnlySpeciesLibrary public class SpeciesLibrary : DataLibrary<ISpecies>, IReadOnlySpeciesLibrary
{ {
private Dictionary<ISpecies, ISpecies> _preEvolutionCache = new();
/// <inheritdoc /> /// <inheritdoc />
public bool TryGetById(int id, [MaybeNullWhen(false)] out ISpecies value) public bool TryGetById(int id, [MaybeNullWhen(false)] out ISpecies value)
{ {
@ -41,4 +53,19 @@ public class SpeciesLibrary : DataLibrary<ISpecies>, IReadOnlySpeciesLibrary
? (value = species) != null ? (value = species) != null
: (value = default) != null; : (value = default) != null;
} }
/// <inheritdoc />
public ISpecies? FindPreEvolution(ISpecies species)
{
if (_preEvolutionCache.TryGetValue(species, out var preEvolution))
return preEvolution;
foreach (var s in this)
{
if (s.EvolutionData.All(e => e.ToSpecies != species.Name))
continue;
_preEvolutionCache[species] = s;
return s;
}
return null;
}
} }