创建一个简单的卡片组C#

时间:2015-10-09 01:53:25

标签: c# arrays loops

我正在尝试用4件套装制作一副52张牌:黑桃,心形,棍棒和钻石。我试图在我的Deck类中创建这个for循环,但似乎遇到了一些关于实际让程序按我想要做的问题。我想也许我可以做4个for循环,但是可以使用if / else-ifs在套牌中创建4个套装吗?

class Deck
{
    private Card[] cards;

    public Deck()
    {
        cards = new Card[52];
        int check = 0;

        for (int suitVal = 1; suitVal < 4; suitVal++)
        {
            for (int rankVal = 1; rankVal < 14; rankVal++)
            {
                if(suitVal == 1)
                {
                    cards[check] = new Card(rankVal, "Spades");
                }
                else if (suitVal == 2)
                {
                    cards[check] = new Card(rankVal, "Hearts");
                }
                else if (suitVal == 3)
                {
                    cards[check] = new Card(rankVal, "Clubs");
                }
                else if (suitVal == 4)
                {
                    cards[check] = new Card(rankVal, "Diamonds");
                }
            }
        }

    }

2 个答案:

答案 0 :(得分:5)

是的,有可能。 共有13张牌和4件套装。这个想法是,对于每件套装,你创造了13张带有所述套装的卡片。伪代码几乎就是你已经拥有的东西:

for each of the four suits
   loop 13 times for said suit

以下是您的代码存在的问题:

1-您的check变量永远不会增加,因此您始终会覆盖位置0上的卡片;每插入一张卡(内循环)后它应该递增

2-你的外围循环只运行3次(i = 1,i = 2,i = 3),并且有4套西装。

如果您需要更多帮助,请与我联系。

答案 1 :(得分:2)

你可以这样做:

class Deck
{
    private Card[] cards;

    public Deck()
    {
        cards =
            new [] { "Spades", "Hearts", "Clubs", "Diamonds", }
                .SelectMany(
                    suit => Enumerable.Range(1, 13),
                    (suit, rank) => new Card(rank, suit))
                .ToArray();
    }
}

或者:

class Deck
{
    private Card[] cards;

    public Deck()
    {
        var query =
            from suit in new [] { "Spades", "Hearts", "Clubs", "Diamonds", }
            from rank in Enumerable.Range(1, 13)
            select new Card(rank, suit);

        cards = query.ToArray();
    }
}

或者:

class Deck
{
    private Card[] cards;

    public Deck()
    {
        cards = new Card[52];
        var index = 0;

        foreach (var suit in new [] { "Spades", "Hearts", "Clubs", "Diamonds", })
        {
            for (var rank = 1; rank <= 13; rank++)
            {
                cards[index++] = new Card(rank, suit);
            }
        }
    }
}