Creating a simple deck of cards C#
Solution 1
Yes, it is possible. There are 13 cards and 4 suits. The idea is that for each suit, you create 13 cards with of said suit. The pseudo code is pretty much what you have already got:
for each of the four suits
loop 13 times for said suit
Here are the problems with your code:
1- Your check
variable is never incremented, so you always overwrite the card on the position 0; It should increment after every card inserted (inner loop)
2- Your outter loop only runs 3 times (i = 1, i = 2, i = 3), and there are 4 suits.
Let me know if you need more help.
Solution 2
You could do it these ways:
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();
}
}
Or:
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();
}
}
Or:
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);
}
}
}
}
crin
Updated on October 01, 2020Comments
-
crin over 3 years
I'm trying to create a deck of 52 cards with the 4 suits: spades, hearts, clubs, and diamonds. I tried to create this for loop in my Deck class but seem to be running into some problems regarding actually getting the program to do what I want. I'm thinking maybe I could do 4 for loops as the assignment hinted at, but is it possible to use if/else-ifs to create 4 suits within the deck?
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"); } } } }
-
Nic over 8 yearsThis seem like school assigned. In my college time...
-
-
crin over 8 yearsThanks for your answer, I ended up doing 4 for loops, though, because I got frustrated. But yeah, now that you've pointed out my errors I see that it is possible to do it with if and else-if statements.
-
Jannik over 8 yearsPlease give this man a thumbs up or accept his answer, he is givng you all you need and this will work the way he pointed it out.
-
crin over 8 yearsCalm down, @Jannik. I don't have the reputation to up-vote answers yet.