You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mastermind/Sources/CoreLibrary/Core/Code.cs

91 lines
2.6 KiB

using CoreLibrary.Exceptions;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
namespace CoreLibrary.Core
{
[DataContract]
public class Code
{
[DataMember]
public ObservableCollection<Jeton> Jetons { get; private init; } = new ObservableCollection<Jeton>();
public int Taille => Jetons.Count;
[DataMember]
public int TailleMax { get; private init; }
public bool Complet => Taille == TailleMax;
public bool Vide => Taille == 0;
public Code(int taille)
{
if (taille < 0)
throw new TailleCodeException(taille);
TailleMax = taille;
}
public void AjouterJeton(Jeton jeton)
{
if (Complet)
throw new CodeCompletException();
Jetons.Add(jeton);
}
public Jeton RecupererJeton(int indice)
{
if (indice < 0 || indice >= Taille)
throw new IndiceCodeException(indice, Taille - 1);
return Jetons.ElementAt(indice);
}
public void SupprimerDernierJeton()
{
if (Vide)
throw new CodeVideException();
Jetons.RemoveAt(Taille - 1);
}
public IReadOnlyList<Indicateur> Comparer(Code code)
{
// Je suis le bon code
List<Indicateur> indicateurs = new List<Indicateur>();
if (!code.Complet)
throw new CodeIncompletException();
if (code.TailleMax != TailleMax)
throw new CodeInvalideException();
List<Jeton?> mesJetons = Jetons.Select(jeton => (Jeton?)jeton).ToList();
List<Jeton?> sesJetons = code.Jetons.Select(jeton => (Jeton?)jeton).ToList();
for (int i = 0; i < mesJetons.Count; ++i)
{
if (mesJetons[i] == sesJetons[i])
{
mesJetons[i] = null;
sesJetons[i] = null;
indicateurs.Add(Indicateur.BonnePlace);
}
}
for (int i = 0; i < sesJetons.Count; ++i)
{
if (sesJetons[i].HasValue && mesJetons.Contains(sesJetons[i]))
{
mesJetons[mesJetons.IndexOf(sesJetons[i])] = null;
sesJetons[i] = null;
indicateurs.Add(Indicateur.BonneCouleur);
}
}
return indicateurs;
}
public override string ToString() => $"Code({Taille})";
}
}