用C#编写程序,模拟从一副扑克牌中随机选取一张牌,显示牌的数值和花色,比如红心 A.
时间: 2024-12-24 08:40:48 浏览: 11
在C#中,我们可以使用`Random`类来生成随机数,并通过数组模拟一副扑克牌的结构。以下是一个简单示例,展示了如何随机选择一张牌并显示其数值和花色:
```csharp
using System;
using System.Collections.Generic;
class Card
{
public enum Suit { Hearts, Diamonds, Clubs, Spades }
public enum Rank { Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace }
public Suit suit { get; set; }
public Rank rank { get; set; }
public override string ToString()
{
switch (rank)
{
case Rank.Two:
return "红心2";
// ... 同样添加其他排至Ace的所有情况
}
return $"未知卡片(Suit: {suit}, Rank: {rank})";
}
}
class PokerDeck
{
private Card[] deck;
public PokerDeck()
{
deck = new Card[52]; // 一副扑克有52张牌
for (int i = 0; i < 4; i++)
{
for (int j = 0; j <= 12; j++) // 每种花色有13张牌
{
deck[i * 13 + j] = new Card { suit = (Suit)i, rank = (Rank)j };
}
}
}
public Card Draw()
{
Random random = new Random();
return deck[random.Next(deck.Length)];
}
}
class Program
{
static void Main()
{
PokerDeck deck = new PokerDeck();
Card drawnCard = deck.Draw();
Console.WriteLine(drawnCard.ToString());
}
}
阅读全文