Best way to represent game card class in C#

后端 未结 7 1854
难免孤独
难免孤独 2021-01-06 01:23

I use class Card which contains 2 enumerated properties (suite - hearts diamonds spades and clubs) and card value from 2 to A. And overrides ToString() method to returns som

相关标签:
7条回答
  • 2021-01-06 01:31

    This card naming system uses a 1 through 4 * 100 (telling the suit flag) + 1 through 13 (for card rank). 500 + 14 through 16 are Little Joker, Big Joker, and Wild.

    public class Card
    {
        short id;
    
        public Card(string zFile)
        {
            this.id = Convert.ToInt16(zFile.Split('.')[0].Trim());
            this.Rank = new Rank(id);
            this.Suit = new Suit(id);
        }
    
        public override string ToString()
        {
            if (Suit.Flag == 5)
                return Suit.Name;
            return string.Concat(Rank.Name, " of ", Suit.Name);
        }
        public override int GetHashCode()
        {
            return id;
        }
    
        public Rank Rank { get; private set; }
        public Suit Suit { get; private set; }
    
        public static Card GetGreaterRank(Card value1, Card value2)
        {               
            return  (value1.Rank >= value2.Rank) ? value1 : value2;                        
        }
    
        public static bool CompareRank(Card value1, Card value2)
        {
            return (value1.Rank.Flag == value2.Rank.Flag);
        }
        public static bool CompareSuit(Card value1, Card value2)
        {
            return (value1.Suit.Flag == value2.Suit.Flag);
        }
    };    
    public abstract class Info
    {
        protected Info(short cardID)
        {
            Flag = SetFlag(cardID);            
        }
    
        protected string SetName(short cardID, params string[] names)
        {
            for (int i = 0; i < names.Length; i++)
            {
               if (Flag == (i + 1))
                  return names[i];
            }
            return "Unknown";
        }
    
        protected abstract byte SetFlag(short cardID);
    
        public static implicit operator byte(Info info)
        {
            return info.Flag;
        }
    
        public byte Flag { get; protected set; }
        public string Name { get; protected set; }
    };
    
    public class Rank : Info
    {
        internal Rank(short cardID) : base(cardID) 
        { 
            string name = SetName(cardID, "A","2","3","4","5","6","7",
                   "8","9","10","J","Q","K","Little Joker","Big Joker","Wild");
            Name = (name == "Unknown") ? string.Concat(name, " Rank") : name;
        }
    
        protected override byte SetFlag(short cardID)
        {
            return Convert.ToByte(cardID.ToString().Remove(0, 1));
        }        
    };
    
    public class Suit : Info
    {
        internal Suit(short cardID) : base(cardID) 
        { 
            string name = SetName(cardID,"Clubs","Diamonds","Hearts","Spades");
            Name = (name == "Unknown") ? string.Concat(name, " Suit") ? name;
        }
    
        protected override byte SetFlag(short cardID)
        {
            return Convert.ToByte(cardID.ToString().Remove(1));
        }
    };
    

    So now if you have your card image file named 101.png and pass it into the Card ctor it will pass to the Rank and Suit getting the info for you. Really all you are doing in giving the image file a code(numeric) for a name.

    0 讨论(0)
  • 2021-01-06 01:35

    You can start enums with number (although it is preferred to start at zero)

    public enum Card
    {
       Two = 2,
       Three,
       Four,
       ...
    }
    
    0 讨论(0)
  • 2021-01-06 01:36

    There's an obvious numeric value for the pip-cards, and we can add J=11, Q=12, K=13.

    It may be more convenient to have A=14 than A=1 depending on the game being modelled (so one can more simply compute different relative values of hands).

    Enums gives no real advantage, especially since enums allow out-of-range values unless you explicitly check for them (e.g. there is nothing to stop someone assigning (CardValue)54 to the card-value enumeration value).

    ToString can be aided with an array of the values {null,"1","2","3","4","5","6","7","8","9","10","J","Q","K"}. Likewise {'♥','♦','♠','♣'} could give a nicer output.

    Parsing always trickier than outputting a string, even if you are very strict in what you accept, as you have to deal with the potential for invalid input. A simple approach would be:

    private Card(string input)
    {
      if(input == null)
        throw new ArgumentNullException();
      if(input.length < 2 || input.length > 3)
        throw new ArgumentException();
      switch(input[input.Length - 1])
      {
        case 'H': case 'h': case '♥':
          _suit = Suit.Hearts;
          break;
        case 'D': case 'd': case '♦':
          _suit = Suit.Diamonds;
          break;
        case 'S': case 's': case '♠':
          _suit = Suit.Spades;
          break;
        case 'C': case 'c': case '♣':
          _suit = Suit.Clubs;
          break;
        default:
          throw new ArgumentException();
      }
      switch(input[0])
      {
        case "J": case "j":
          _cardValue = 11;
          break;
        case "Q": case "q":
          _cardValue = 12;
          break;
        case "K": case "k":
          _cardValue = 13;
          break;
        case "A": case "a":
          _cardValue = 1;
          break;
        default:
          if(!int.TryParse(input.substring(0, input.Length - 1), out _cardValue) || _cardValue < 2 || _cardVaue > 10)
            throw new ArgumentException;
          break;
      }
    }
    public static Card Parse(string cardString)
    {
      return new Card(cardString);
    }
    

    You might want to add a static method that read a larger string, yield returning cards as it parsed, to allow for easier encoding of several cards.

    0 讨论(0)
  • 2021-01-06 01:41

    Couldn't you assign Jack, Queen, King, and Ace to be 11, 12, 13, and 14, respectively? It'd end up looking something like:

    public class Card
    {
        public int Value { get; private set; }
        public enum SuitType
        {
            Clubs, Spades, Hearts, Diamonds
        }
        public SuitType Suit { get; private set; }
        public Card(int value, SuitType suit)
        {
            Suit = suit;
            Value = value;
        }
        public Card(string input)
        {
            if (input == null || input.Length < 2 || input.Length > 2)
                throw new ArgumentException();
            switch (input[0])
            {
                case 'C': case 'c':
                    Suit = SuitType.Clubs;
                    break;
                case 'S': case 's':
                    Suit = SuitType.Spades;
                    break;
                case 'H': case 'h':
                    Suit = SuitType.Hearts;
                    break;
                case 'D': case 'd':
                    Suit = SuitType.Diamonds;
                    break;
                default:
                    throw new ArgumentException();
            }
            int uncheckedValue = (int)input[1];
            if (uncheckedValue > 14 || uncheckedValue < 1)
                throw new ArgumentException();
            Value = uncheckedValue;
        }
        public string encode()
        {
            string encodedCard = "";
            switch (Suit)
            {
                case SuitType.Clubs:
                    encodedCard += 'c';
                    break;
                case SuitType.Spades:
                    encodedCard += 's';
                    break;
                case SuitType.Hearts:
                    encodedCard += 'h';
                    break;
                case SuitType.Diamonds:
                    encodedCard += 'd';
                    break;
            }
            encodedCard += (char) Value;
            return encodedCard;
        }
        public override string ToString()
        {
            string output = "";
            if (Value > 10)
            {
                switch (Value)
                {
                    case 11:
                        output += "Jack";
                        break;
                    case 12:
                        output += "Queen";
                        break;
                    case 13:
                        output += "King";
                        break;
                    case 14:
                        output += "Ace";
                        break;
                }
            }
            else
            {
                output += Value;
            }
            output += " of " + System.Enum.GetName(typeof(SuitType), Suit);
            return output;
        }
    }
    

    Edit: I added some string functionality. I took structure of Card(string input) from Jon Hanna's answer.

    0 讨论(0)
  • 2021-01-06 01:46

    When I first started on the card.dll, I was using enumerations for suits and card rankings but then I didn't want to have to deal with that same issue and writing extra code to compensate for the strings, there for I wrote a abstract class Info with only two variables (Flag (byte)) and (Name(string)) to be implemented by the Rank class and Suit class which would be members of the Card class. I have found this to work a lot better for naming conventions and filtering purposes. I love using enums but having to work around variable naming can be a hassle so sometimes it is best not to if you have to get the variable name as string.

    So when the Card constructor get called the card ID is entered and then it passes into the Rank and Suit which will then separate what the ID means in code (101 = 100 (suit flag) + 1 (rank flag)). The protected abstract SetName(int cardID) and SetFlag(int cardID) while handle the rest from there in the info's constructor via Rank and Suit. No more issues with the enumeration and it can still be filtered by number via the Flag.

    0 讨论(0)
  • 2021-01-06 01:48

    I would probably start out with 2 enums, 1 representing the Suits and 1 representing the Faces. Then declare a public property "Suit" and a public property "Face" based off of these enums. You will also probably need an array with the different unique values that a card can have (i.e. 1 throught 13).

    0 讨论(0)
提交回复
热议问题