无法获取shuffle方法来收集列表
本文关键字:列表 方法 获取 shuffle | 更新日期: 2023-09-27 18:20:01
我遇到了这个愚蠢的问题,我不知道如何解决,我正在创建一个21点游戏,我有一个带有Deck()和Shuffle()方法的卡类,以及一个将分发卡的发牌器类。
shuffle方法是我在这个网站上得到的一个扩展方法,很有趣,但我无法让它从Deck()方法接收卡片列表。。。
我最初确实使用了一本字典,在整理字典时遇到了麻烦,并在这个网站上寻求帮助他们建议使用一个列表,现在我在这里。
这是卡和经销商类别
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;
}
}
批评是重点推荐,因为这是你学习的方式,但请记住,我还是一个初学者,根本没有经验。
感谢
我认为将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
,…)
此外,我建议通过以下方式使其更清洁:
- 为卡实现类(Suite,Face)
- 为牌组(牌的集合)实现一个类
- 让所有东西都是不可变的(从外表上看,这意味着:你可以按原样洗牌,但不要让别人改变你的牌组-为界面创建新的牌组,例如,经销商抽一张牌应该给你一张牌和另一副牌(没有这张牌)-这提高了代码的可测试性