我有这个愚蠢的问题而且我不知道如何修复,我正在创建一个二十一点游戏,我有一个带有Deck()和Shuffle()方法的卡片类,以及一个可以发放卡片的经销商类
shuffle方法是一个扩展方法,我在这个网站上搞笑了但我不能让它从Deck()方法接收卡片列表......
我原本使用字典并且无法改组字典并在此网站上寻求帮助Here 他们建议使用一个列表,现在就在这里。
这是卡片和经销商类
Card.cs
public static class Card
{
private static List<string> deckOfCards = new List<string>();
private static string[] Suite = new string[4] {"Clubs", "Hearts", "Spades", "Diamonds" };
private static string[] FaceValue = new string[13] {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
public static void Deck()
{
for (int s = 0; s < 4; s++ )
{
string sut = Suite[s];
for (int fV = 0; fV < 13; fV++)
{
string value = FaceValue[fV];
deckOfCards.Add(sut + value);
}
}
// End of For loop.
Shuffle(deckOfCards);
}
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
Dealer.cs
class Dealer
{
private List<string> randomisedCards = new List<string>();
public Dealer()
{
randomisedCards.Shuffle();
}
public string dealCard()
{
string randCard = randomisedCards[0];
randomisedCards.RemoveAt(0);
return randCard;
}
}
批评是值得推荐的,因为这是你学习的方式,但请记住,我仍然是初学者,根本没有经验。
由于
答案 0 :(得分:2)
我认为将 Deck 保存为班级中的静态值是一个可怕的想法,我建议这样做:
public static class Cards
{
private static string[] Suite = new string[4] {"Clubs", "Hearts", "Spades", "Diamonds" };
private static string[] FaceValue = new string[13] {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King" };
public static List<string> CreateDeck()
{
var deck = new List<string>();
for (int s = 0; s < 4; s++ )
{
string sut = Suite[s];
for (int fV = 0; fV < 13; fV++)
{
string value = FaceValue[fV];
deck.Add(sut + value);
}
}
// End of For loop.
Shuffle(deck);
return deck;
}
private static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
像这样使用它:
class Dealer
{
private List<string> randomisedCards;
public Dealer()
{
randomisedCards = Cards.CreateDeck();
}
public string dealCard()
{
string randCard = randomisedCards[0];
randomisedCards.RemoveAt(0);
return randCard;
}
}
请注意,我没有检查您的代码(CreateDeck
,Shuffle
,...)
我还建议通过以下方式制作这种清洁剂: