Page 1 of 1

Checking a variable against itself?

Posted: July 15th, 2020, 11:11 pm
by Lividpayment
if (wnd.mouse.RightIsPressed())
{
BoardColor = Colors::Blue;
}
else
{
BoardColor = BoardColorAfterChanged;
}


Can anyone help with this problem? Basically whenever the right is pressed the board will change color, it works, but I was wondering there was a more elegant solution to reverse it back to the original as opposed to assigning a different variable? I was thinking a bool statement, but it didn't seem to do anything.

Thanks!

Re: Checking a variable against itself?

Posted: July 16th, 2020, 11:56 am
by krautersuppe
argument of if-statement is already a bool.

Code: Select all

if(check_is_true){
dothis;
}
else{
dothat;
}
Instead of a variable you can just assign one of predefined values like:
BoardColor = Colors::Green;

Re: Checking a variable against itself?

Posted: July 16th, 2020, 9:22 pm
by albinopapa
I suppose it depends on what you want to do for the behavior. Does the board only change color while right button is down, or are you wanting to toggle it so each press of the right button changes the color between default color and alternate color.

Your code looks like it just sets the color to blue while the right button is down instead of toggling, so if that is the desired result, then what you have really can't be improved upon other than maybe using the ternary operator: ?:

BoardColor = wnd.mouse.RightIsPressed() ? Colors::Blue : BoardColorAfterChanged;

If the BoardColorAfterChanged is suppose to be a toggle, allowing you to cycle through a color palette, then there is something else you can do, but it will still be similar.

Code: Select all

// Board class members
static constexpr int num_colors_in_palette = 5;
static constexpr std::array<Color, num_colors_in_palette> colors = { Colors::Red, Colors::Green, Colors::Blue, Colors::Magenta, Colors::Yellow };
int color_index = 0;

// Code in function to change color
if( wnd.mouse.RightIsPressed() )
    color_index = ( color_index + 1 ) % num_colors_in_palette;

BoardColor = colors[ color_index ];