簡體   English   中英

如何定義一個字符串大於另一個字符串? (C#)(入門)

[英]How to Define that One String is Greater than Another? (C#) (Beginner)

我對編碼非常陌生,因此答案很明顯。 我必須制作紙牌游戲War。 我已經為套牌的一部分創建了這樣的字符串列表:

List<string> userDeck = new List<string>
        {
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "Jack",
            "Queen",
            "King",
            "Ace",
        };

有沒有一種方法可以指示計算機“傑克”大於“ 10”,“女王”大於“傑克”,依此類推? 我不確定應該在哪里或應該怎么做。

或者 ,如果您對我應該如何做還有其他建議,請告訴我。 我必須使用列表。 最初,我列出了一個整數列表,但是我不知道為顯示目的分配諸如“ Jack”,“ Queen”,“ King”等名稱的簡單方法。

任何幫助將不勝感激。

嘗試創建一個稱為“卡”的對象。 該對象可以包含多個值。 例如:

public class MyCard
{
     public string Name {get;set;}
     public int Value {get;set;}

     public MyCard(string name, int value)
     {
         this.Name = name;
         this.Value = value;
     }
}

創建該對象后,將在列表中使用它。

List<MyCard> userDeck = new List<MyCard>();

您可以通過以下方式填寫列表:

usertDeck.Add(new MyCard("2", 1));
....
usertDeck.Add(new MyCard("K", 11));

因此,要比較2張卡,只需使用“ Value”變量進行檢查

與Vincius的答案類似,但進行了一些更改以提高可用性:

  enum Suit
  {
    Clubs = 1,
    Diamonds = 2,
    Hearts = 3,
    Spades = 4
  }

  class Card
  {
    private static readonly Dictionary<string, int> rankMap = new Dictionary<string, int>()
    {
      {"2", 2 },
      {"3", 3 },
      {"4", 4 },
      {"5", 5 },
      {"6", 6 },
      {"7", 7 },
      {"8", 8 },
      {"9", 9 },
      {"10", 10 },
      {"Jack", 11 },
      {"Queen", 12 },
      {"King", 13 },
      {"Ace", 14 },
    };


    private Suit suit;
    private string rank;

    public Suit Suit => suit;
    public string Rank => rank;
    public int Value { get { return rankMap[rank]; } }

    public Card(Suit s, string r)
    {
      suit = s;
      rank = r;
    }
  }

使用方式:

  Card c1 = new Card(1, "Jack");  // 1 is Clubs
  Card c2 = new Card(4, "Queen"); // 4 is Spades
  Console.WriteLine(c1.Value); // prints 11
  Console.WriteLine(c2.Value); // prints 12

重構代碼(達到每張卡的要求值)的最簡單方法是在通用List中使用Tuple而不是字符串類型,如下所示:

List<Tuple<int,string>> userDeck = new List<Tuple<int,string>>
        {
            new Tuple<int,string>(2,"2"),
            new Tuple<int,string>(3,"3"),
            new Tuple<int,string>(4,"4"),
            new Tuple<int,string>(5,"5"),
            new Tuple<int,string>(6,"6"),
            new Tuple<int,string>(7,"7"),
            new Tuple<int,string>(8,"8"),
            new Tuple<int,string>(9,"9"),
            new Tuple<int,string>(10,"10"),
            new Tuple<int,string>(11,"Jack"),
            new Tuple<int,string>(12,"Queen"),
            new Tuple<int,string>(13,"King"),
            new Tuple<int,string>(14,"Ace"),
        };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM