using System.Collections;
using PkmnLib.Static.Utils;
namespace PkmnLib.Dynamic.Models;
///
/// A collection of Pokemon.
///
public interface IPokemonParty : IReadOnlyList, IDeepCloneable
{
event EventHandler<(IPokemon?, int index)>? OnSwapInto;
event EventHandler<(int index1, int index2)>? OnSwap;
///
/// Sets the Pokemon at an index to a Pokemon, returning the old Pokemon.
///
IPokemon? SwapInto(IPokemon? pokemon, int index);
///
/// Swaps two Pokemon in the party around.
///
void Swap(int index1, int index2);
///
/// Whether the party has any Pokemon that could be used in battle.
///
///
/// This will return false if all Pokemon are fainted, or eggs, etc.
///
bool HasUsablePokemon();
///
/// Packs the party so that all Pokémon are at the front, and the empty slots are at the back.
///
void Pack();
}
///
public class PokemonParty : IPokemonParty
{
private readonly IPokemon?[] _pokemon;
///
public PokemonParty(int size)
{
_pokemon = new IPokemon[size];
}
///
public event EventHandler<(IPokemon?, int index)>? OnSwapInto;
///
public event EventHandler<(int index1, int index2)>? OnSwap;
///
/// Sets the Pokemon at an index to a Pokemon, returning the old Pokemon.
///
public IPokemon? SwapInto(IPokemon? pokemon, int index)
{
var old = _pokemon[index];
_pokemon[index] = pokemon;
OnSwapInto?.Invoke(this, (pokemon, index));
return old;
}
///
/// Swaps two Pokemon in the party around.
///
public void Swap(int index1, int index2)
{
(_pokemon[index1], _pokemon[index2]) = (_pokemon[index2], _pokemon[index1]);
OnSwap?.Invoke(this, (index1, index2));
}
///
public bool HasUsablePokemon() => _pokemon.Any(p => p is { IsUsable: true });
///
public IEnumerator GetEnumerator() => ((IEnumerable)_pokemon).GetEnumerator();
///
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
///
public int Count => _pokemon.Length;
///
public IPokemon? this[int index] => _pokemon[index];
///
public void Pack()
{
// Pack the party so that all Pokémon are at the front.
for (var i = 0; i < _pokemon.Length; i++)
{
if (_pokemon[i] != null)
continue;
for (var j = i + 1; j < _pokemon.Length; j++)
{
if (_pokemon[j] == null)
continue;
Swap(i, j);
break;
}
}
}
}