Search code examples
c#buttonrandomtic-tac-toe

C# WPF How do i change the content to a random button?


I am trying to make a Tic Tac Toe game in Silverlight that can be played in 1 player mode. So for that after clicking on any button and change it's content to "X" or "O" i need to change the content of a random button.

I've tried making a list of all buttons and getting a random value:

    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;
    }

but i don't know how to make my random string a Button so i can call the following method:

    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);
    }

Any ideas? thank you!


Solution

  • Make a list of button references instead:

    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);
        }
    }
    

    Not sure why the button with index zero isn't to be used, though...