Files
Memory/Memory.Logic/Game.cs
KaseToatz1337 4c01b5ae79 Add comments
2024-11-07 10:18:20 +01:00

104 lines
3.5 KiB
C#

namespace Memory.Logic
{
public class Game(IScoreHandler scoreHandler, string player, int deckSize)
{
public const int MAXPOINTS = 100;
public const int MINPOINTS = 10;
public const int MAXTIME = 10000;
public const int STARTSCORE = 100;
public int DeckSize { get; } = deckSize;
public int GridSize { get; } = GetGridSize(deckSize).Rows;
public List<Card> Cards { get; } = CreateDeck(deckSize);
public IScoreHandler ScoreHandler { get; } = scoreHandler;
public long StartTime { get; } = DateTimeOffset.Now.ToUnixTimeMilliseconds();
public int Attempts { get; set; } = 0;
public Score Scoring { get; } = new(player, 0);
// Formula to calculate score
public void CalculateScore(long endTime)
{
Scoring.Points = (int)(Math.Pow(DeckSize * 2, 2) / ((endTime - StartTime) / 1000.0 * Attempts) * 1000.0);
}
// Get the optimal grid size for the current amount of cards
public static Deck GetGridSize(int deckSize)
{
for (int i = (int)Math.Sqrt(deckSize * 2); i > 0; i--)
{
if (deckSize * 2 % i == 0)
{
return new(i, deckSize * 2 / i);
}
}
return new(1, deckSize * 2);
}
// Create a random set of cards
public static List<Card> CreateDeck(int pairs)
{
List<Card> cards = [];
for (int i = 1; i < pairs + 1; i++)
{
cards.Add(new(i));
cards.Add(new(i));
}
Random random = new();
return [..cards.OrderBy(card => random.Next())];
}
public Card? GetChoice1()
{
return Cards.FirstOrDefault(card => card.IsChoice1);
}
public Card? GetChoice2()
{
return Cards.FirstOrDefault(card => card.IsChoice2);
}
public bool IsFinished()
{
return Cards.All(card => card.Completed);
}
public void ClickCard(Card card)
{
Card? choice1 = GetChoice1();
Card? choice2 = GetChoice2();
if (!card.Completed)
{
// Set the card to choice1 or choice2 depending on the context
if ((choice1 == null && choice2 == null) || (choice1 != null && choice2 != null))
{
if (choice1 != null)
{
choice1.IsChoice1 = false;
}
if (choice2 != null)
{
choice2.IsChoice2 = false;
}
card.IsChoice1 = true;
}
else if (choice1 != null && choice2 == null && choice1 != card)
{
card.IsChoice2 = true;
Attempts++;
if (choice1.Matches(card))
{
// If card matches, mark as complete and check if the game is finished
choice1.Completed = true;
card.Completed = true;
if (IsFinished())
{
CalculateScore(DateTimeOffset.Now.ToUnixTimeMilliseconds());
ScoreHandler.WriteScore(Scoring);
}
}
}
}
}
}
}