c#写一个从一副扑克牌抽取4张牌
时间: 2024-12-08 10:17:51 浏览: 15
在C#中,你可以使用List<T>容器和随机数生成器来模拟抽取扑克牌的过程。这里是一个简单的示例,假设我们有一副扑克牌包含52张牌(四种花色:红桃、黑桃、梅花、方块,每种13张牌),我们可以创建一个Deck类表示整副牌,并抽牌方法DrawFourCards:
```csharp
using System;
using System.Collections.Generic;
public class Card
{
public string Suit { get; set; } // 花色
public int Rank { get; set; } // 排序,如1到13
public Card(string suit, int rank)
{
Suit = suit;
Rank = rank;
}
public override string ToString()
{
return $"{Suit} of {Rank}";
}
}
public class Deck
{
private List<Card> cards = new List<Card>();
public Deck()
{
for (int suit = 0; suit < 4; suit++)
{
for (int rank = 1; rank <= 13; rank++)
{
cards.Add(new Card(suit switch
{
0 => "红桃",
1 => "黑桃",
2 => "梅花",
3 => "方块",
_ => throw new ArgumentException("Invalid suit")
}, rank));
}
}
}
public List<Card> DrawFourCards()
{
if (cards.Count < 4)
{
throw new InvalidOperationException("牌不足,无法抽取四张");
}
var drawnCards = new List<Card>();
foreach (var _ in Enumerable.Range(0, 4))
{
drawnCards.Add(cards[Random.Next(cards.Count)]);
cards.RemoveAt(Random.Next(cards.Count)); // 移除已抽取的牌
}
return drawnCards;
}
}
public static void Main()
{
var deck = new Deck();
var drawnCards = deck.DrawFourCards();
Console.WriteLine("抽取的四张牌:");
foreach (var card in drawnCards)
{
Console.WriteLine(card);
}
}
```
在这个例子中,`Deck`类初始化了所有牌,然后`DrawFourCards()`方法会随机抽取并移除四张牌。
阅读全文