我正在用C#开发一个程序,你有一个按钮,它会从预先确定的选择中选择两张随机卡片。例如,我从 5 张牌开始,将从中选择:黑桃王牌、黑桃王牌、红心王牌、俱乐部五张和钻石王牌。现在它将比较这两张牌,确定哪张牌更高,并使其成为赢家,黑桃>红心>俱乐部>钻石和王牌较低。因此,黑桃王牌将赢得两颗钻石。我制作了一个卡牌类,在其中设置了花色和等级:
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds
}
public enum Ranks
{
Ace,
_2,
_3,
_4,
_5,
_6,
_7,
_8,
_9,
_10,
Jacks,
Queen,
King
}
//Private instance variables suit and rank
private Suits suit;
private Ranks rank;
//Provide properties for suit and rank that insure they can only be set to valid values
public Suits Suit
{
get
{
return this.suit;
}
set
{
this.suit = value;
}
}
public Ranks Rank
{
get
{
return this.Rank;
}
set
{
this.rank = value;
}
}
//Provide a default constructor (no parameters) that sets the card to Ace of Spades.
public CardClass()
{
// Use the properties to set these values
this.Rank = Ranks.Ace;
this.Suit = Suits.Spades;
}
// Provide an explicit constructor with parameters for ALL instance variables.
public CardClass(Ranks rank, Suits suit)
{
//Use the properties to set these values
this.Rank = rank;
this.Suit = suit;
}
现在,对于我的按钮单击,我对其进行了设置,以便它将选择2个不同的数字,一个用于玩家1,一个用于玩家2:
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int play1choice, play2choice;
private void btnCard_Click(object sender, EventArgs e)
{
Random player1 = new Random();
int Player1 = (player1.Next(5) + 1);
Random player2 = new Random();
int Player2 = (player2.Next(5) + 1);
}
}
}
有没有办法为数字设置某些卡?因此,如果随机数生成器选择 1,它会将其分配给黑桃王牌,2 使其成为黑桃七,依此类推。
创建一个将生成五个初始卡的方法(请参阅GetFiveInitialCards
(:
public enum Suits
{
Spades,
Hearts,
Clubs,
Diamonds
}
public enum Ranks
{
Ace,
_2,
_3,
_4,
_5,
_6,
_7,
_8,
_9,
_10,
Jacks,
Queen,
King
}
public class CardClass
{
public static CardClass[] GetFiveInitialCards()
{
return new CardClass[] {
new CardClass(Suits.Spades, Ranks.Ace),
new CardClass(Suits.Spades, Ranks._7),
new CardClass(Suits.Hearts, Ranks.Ace),
new CardClass(Suits.Clubs, Ranks._5),
new CardClass(Suits.Diamonds, Ranks._2)
};
}
public Suits Suit { get; }
public Ranks Rank { get; }
public CardClass(Suits suit, Ranks rank)
{
this.Suit = suit;
this.Rank = rank;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int play1choice, play2choice;
private readonly Random rnd = new Random();
private void btnCard_Click(object sender, EventArgs e)
{
CardClass[] initialCards = CardClass.GetFiveInitialCards();
int Player1 = (rnd.Next(5) + 1);
CardClass player1Card = initialCards[Player1];
int Player2 = (rnd.Next(5) + 1);
CardClass player2Card = initialCards[Player2];
}
}