+ 3
Playing cards- enums or arrays?
Just a quick question- when making a deck of cards, is it better to make the ranks and suits an enum or an array? This is just out of curiousity and I feel like I have seen both mentioned? I am not writing code for any game, I am just trying to find ways to practice coding and it seems a deck of cards can be more complicated than I thought 😅 thanks for your time and I hope for a good mini discussion :p
4 Antworten
+ 2
Definitely enums:
public enum Suit
{
Club,
Diamond,
Heart,
Spade
}
public enum Rank
{
Ace = 1,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Ten,
Jack,
Queen,
King
}
I worked on a card library earlier this year, you can check it out.
It's been copied and pasted from Visual Studio so it's a bit of a mess. Normally I'd separate the classes and enums into separate files, but I think you get the picture.
The code basically shuffles a deck of cards using Random.Next. Hope this is of some help.
https://code.sololearn.com/cuxj2CrmYy2L/?ref=app
+ 2
ah I was close! I keep trying to find a way to iterate through the enum's members to assign the rank and value like:
for (int i = 0; i < 4; i++;) {card.CardSuit = Enum.GetValue (Suit [i]};
but it yells at me for using Suit (which is my enum) saying its a type and can't be used like that. :/ I'm continually reading over your code to understand! thanks so much!
+ 2
No problem. I do agree, though, that it's more complicated than you first think. I remember having it quite clear in my mind, but was struggling to link the classes, enums and methods all together.
But using the class diagrams in Visual Studio definitely helps. It gives you a visual representation of what's going on and you can easily see how it all links together. Once you're happy with it, VS can then put all the code in automatically. It's very powerful and definitely worth checking out.
0
Is more significant / human readable using enums if the values are well bounded.
In other problems.. maybe a factory or other patter that provides better flexibility