【问题标题】:C# WPF How do i change the content to a random button?C# WPF 如何将内容更改为随机按钮?
【发布时间】:2012-09-30 22:22:38
【问题描述】:

我正在尝试在 Silverlight 中制作一款可以在 1 人模式下玩的井字游戏。 因此,在单击任何按钮并将其内容更改为“X”或“O”后,我需要更改随机按钮的内容。

我尝试列出所有按钮并获取随机值:

    public List<string> avail = new List<string>() { "button1", "button2", "button3", "button4", "button5", "button6", "button7", "button8", "button9" };

    public string Ran()
    {
        Random b1 = new Random();
        int index = b1.Next(avail.Count); 
        if (index > 0)
            return avail[index];
        else
            return null;
    }

但我不知道如何使我的随机字符串成为按钮,所以我可以调用以下方法:

    public void buttonchange(Button b)
    {
        if (b.Content.ToString() == "")
            if (x == true)
            {
                x = false;
                b.Content = "X";
            }
            else
            {
                x = true;
                b.Content = "O";
            }
        if(b.Name!=null)
            avail.Remove(b.Name);
    }

有什么想法吗? 谢谢!

【问题讨论】:

    标签: c# button random tic-tac-toe


    【解决方案1】:

    改为列出按钮引用:

    public List<Button> avail = new List<Button>() { button1, button2, button3, button4, button5, button6, button7, button8, button9 };
    
    public Button Ran()
    {
        Random b1 = new Random();
        int index = b1.Next(avail.Count); 
        if (index > 0) {
            return avail[index];
        } else {
            return null;
        }
    }
    
    public void buttonchange(Button b)
    {
        if(b != null) {
            if (b.Content.ToString() == "") {
                b.Content = x ? "X" : "O";
                x = !x;
            }
            avail.Remove(b);
        }
    }
    

    不知道为什么不使用索引为零的按钮...

    【讨论】:

    • 我不认为有索引 0... 在索引中存储了avail.Count
    • 好的。我也试过这个。但现在我收到以下错误消息:“字段初始化程序无法引用非静态字段方法或属性'project.ttt.button1'”(对于“可用”列表中的每个元素)请注意“button1”“button2 ““button3”等是我通过拖放手动添加到 ttt.xaml 界面中的 9 个按钮的名称。(也许有帮助)。谢谢!
    • 所以...我在新的游戏按钮点击方法中添加了列表中的每个按钮。它奏效了……终于……谢谢Guffa。希望这对其他人也有帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 2018-11-15
    • 2019-06-02
    • 2021-08-24
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多