I have a match 3-4 game and the blocks can be one of 7 colors. There are an addition 7 blocks that are a mix of the original 7 colors so for example there is a red and blue block and there is also a red/blue block which can be matched with either the red or the blue. My original thought is just to use binary operations so.

int red     = 0x000000001;
int blue    = 0x000000010;
int redblue = 0x000000011;

Then just do an & operation so see if they match. Does this sound like a decent plan or am I over complicating it?


Better yet so it's more readable.

int red = 1;
int blue = 2;
int red_blue = 3;
int yellow = 4;
int red_yellow = 5;

maybe as defines or static vars?

  • 2
    \$\begingroup\$ sounds like a good plan to me, it´s flexible, fast and pretty simple. Note that 0x000000010 is 16, not 2, since 0x... is allways a hexadecimal number. \$\endgroup\$
    – Luis W
    Aug 3 '13 at 11:17

This is probably the easiest way to do it - not overcomplicating it at all. However, I'd work with constants rather than variables (assuming those are available in your chosen language).

const int COLOR_ALL      = 0xffff; // or just -1
const int COLOR_RED      = 0x0001;
const int COLOR_BLUE     = 0x0002;
const int COLOR_YELLOW   = 0x0004;
const int COLOR_RED_BLUE = COLOR_RED | COLOR_BLUE; // saves you doing the math yourself (error prone)

Then, to verify the colors match you can simply do something like this:

// Assumption: picked_blocks is an array with the colors of the selected blocks

int check = COLOR_ALL;
for (int i = 0; i < num_picked_blocks && check; i++) // Whether "&& check" is worth it, really depends on the maximum number of blocks to check
    check &= picked_blocks[i]; // This will essentially remove all colors from check that aren't in this block

if (check)
    ; // Choice is valid.
    ; // Choice is invalid.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .