1

我对 C# 很陌生,我想做一个纸牌游戏。我所拥有的是一个卡片列表(字符串),其名称如c6, s3, h11, d13wherecharacter represents the colournumber represents the value. 当按下按钮时,程序会从列表中获取一个随机字符串并将其显示在文本框中。从那里开始,游戏的重点是猜测下一张随机牌的值是比前一张牌高还是低。

我想要做的是从文本框中获取字符串并将其转换为 int,以便我可以将前一张卡的值与新卡进行比较。唯一的问题是我如何摆脱cinc6以便我可以使用parse.

这是我的代码。

public partial class MainWindow : Window
{
    static Random rndmlist = new Random();
    Random rndm = new Random();
    List<string> deck = new List<string>();
    int score = 0;
    public MainWindow()
    {
        InitializeComponent();
    }

    private void test_Click(object sender, RoutedEventArgs e)
    {
        //disregard this
        foreach (string j in deck)
        {
            testbox.Text += j + ", ";
        }
    }

    private void btnstart_Click(object sender, RoutedEventArgs e)
    {
        //this is where i add all the cards to the list
        for (int i = 1; i <= 13;)
        {
            deck.Add("c" + i);
            i++;
        }
        for (int i = 1; i <= 13; )
        {
            deck.Add("s" + i);
            i++;
        }
        for (int i = 1; i <= 13; )
        {
            deck.Add("h" + i);
            i++;
        }
        for (int i = 1; i <= 13; )
        {
            deck.Add("d" + i);
            i++;
        }
    }

    private void btnbegin_Click(object sender, RoutedEventArgs e)
    {
        //this is where i take a random card from the list and display it in textBox2
        int r = rndmlist.Next(deck.Count);
        textBox2.Text = ((string)deck[r]);

        //disregard this
        testbox.Text += ((string)deck[r]) + ", ";
        deck.Remove((string)deck[r]);
    }

    private void btnhigh_Click(object sender, RoutedEventArgs e)
    {
        //this is where i want to compare the cards.
    }
}

预先感谢您阅读本文。(:

4

5 回答 5

5

我最好创建一个类Card,它代表一张卡片,有 2 个属性:ColorNumber实现的方法Card.ParseFromString()

于 2013-05-28T11:04:23.607 回答
1

尝试这个,

 string SubString = MyString.Substring(1);

但要注意如果字符串为空,这是一个错误情况。

于 2013-05-28T11:02:22.900 回答
1

假设数字前总是有一个(并且只有一个)字符,您可以简单地执行以下操作:

string numberAsString = "c2".Substring(1);

并使其成为int

int number = Int32.Parse(numberAsString);
于 2013-05-28T11:02:49.850 回答
0

您可以使用正则表达式替换所有字母字符,例如

string result = Regex.Replace(myString, @"[a-zA-Z\s]+", string.Empty);
于 2013-05-28T11:02:45.633 回答
0
string str = "c12";
var noChars = str.SubString(1); // take a new string from index 1
var number = Int32.Parse(noChars);
于 2013-05-28T11:03:07.307 回答