Home > Back-end >  How to check if two button in a list have the same opacity?
How to check if two button in a list have the same opacity?

Time:03-30

I have an issue with my application. I'm creating a "simple" mobile game where I have a list of a button that have an opacity of 0.4 and I take one random button in the list and set it opacity to 1. And my point is to have two button generated, so for now I just called the function twice at the start but the problem is that when the two button are the same it generates just one after. I hope you'll understand (I'm French).

'''        void ChooseFirstRandomButton()
    {
        var rand = new Random();

        var buttonList = new List<Button> { 
            one, two, three, four, five, six, seven, eight, nine,
            ten, eleven, twelve, thirteen, fourteen, fifteen,
            sixteen, seventeen, eighteen, nineteen, twenty,
            twentyone, twentytwo, twentythree, twentyfour
        };

        int index = rand.Next(buttonList.Count);
        var randomButton = buttonList[index];
        var randomButtonOpacity = randomButton.Opacity;
        randomButton.Opacity = 1;
    }
'''

The "one", "two", ... are the name of my buttons.

Thank you for your answers.

CodePudding user response:

use a loop to continue picking numbers until you get one that hasn't already been chosen

// initialize your list of buttons and random seed 
// before the loop

bool loop = true;

while (loop)
{
    int index = rand.Next(buttonList.Count);
    var randomButton = buttonList[index];

    // if it's not set, set it and exit loop
    if (randomButton.Opacity != 1) 
    {
       randomButton.Opacity = 1;
       loop = false;
    }
}

CodePudding user response:

As from video you provided and your description "buttons meet each other" you just need to improve your algorithm:

  1. create somewhere outside of the function a global variable:
    int opacity_1_index = -1;
  1. after choosing random index, check if it is not equal to the one remembered:
    int index = rand.Next(buttonList.Count);
    if (index == opacity_1_index)
    {
            // exit function and call it again
    }
  1. else remember this index and do the rest:
    else
    {
            opacity_1_index = index; // add this line
            var randomButton = buttonList[index];
            var randomButtonOpacity = randomButton.Opacity;
            randomButton.Opacity = 1;
    }
  • Related