public enum Suit
{
Hearts,
Diamonds,
Clubs,
Spades
}
public enum Rank
{
Two = 2,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King,
Ace
}
public class Card
{
public Suit Suit { get; }
public Rank Rank { get; }
public Card(Suit suit, Rank rank)
{
Suit = suit;
Rank = rank;
}
public override string ToString()
{
return $"{Rank} of {Suit}";
}
}
internal class Deck
{
private List _cards;
private Random _random = new Random();
public Deck()
{
_cards = new List();
InitializeDeck();
}
private void InitializeDeck()
{
_cards.Clear();
foreach (Suit suit in Enum.GetValues(typeof(Suit)))
{
foreach (Rank rank in Enum.GetValues(typeof(Rank)))
{
_cards.Add(new Card(suit, rank));
}
}
}
public void Shuffle()
{
for (int i = _cards.Count - 1; i > 0; i--)
{
int j = _random.Next(i + 1);
var temp = _cards[i];
_cards[i] = _cards[j];
_cards[j] = temp;
}
}
public Card DrawCard()
{
if (_cards.Count == 0)
throw new InvalidOperationException("No cards left in the deck.");
Card card = _cards[0];
_cards.RemoveAt(0);
return card;
}
public int CardsRemaining => _cards.Count;
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Deck deckofcards = new Deck();
private void button1_Click(object sender, EventArgs e)
{
deckofcards.Shuffle();
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(deckofcards.DrawCard());
}
Console.WriteLine($"Cards remaining: {deckofcards.CardsRemaining}");
}