View Single Post
Codemonkey's Avatar Codemonkey Codemonkey is offline Super Moderator 2006-11-07 #24 Old  
021 - Bits as Flags
Last edited by Codemonkey : 2006-11-12 at 00:38.
 
If you want a clean and efficient way of testing against flags, you can use bit-wise operators.

Define your flags as numbers like 2, 4, 8, 16 (double for each new flag constant):

ActionScript Code:
  1. var FUNNY = 2;
  2. var NOISY = 4;
  3. var HANDSOME = 8;
  4. var COOL = 16;
  5. var NERDY = 32;
  6. var SUPERMANLIKE = 64;
Then, you can combine these flags - and lateron check against individual flags - using the bitwise operator 'or':

ActionScript Code:
  1. var splat:Number = COOL | NERDY; // 'or' the bits!
  2. var codemonkey:Number = FUNNY | HANDSOME | COOL | SUPERMANLIKE;
To check if Splat is cool, use the bitwise operator 'and' to check the combined flags against the COOL flag:

ActionScript Code:
  1. if (splat & COOL) {
  2. trace("Splat is cool!");
  3. }

The key to this mechanism is being able to use many different flags together in one number variable. Take the Array class for example. If you want to sort an Array with the method Array.sort(), you can use constants from the Array class to indicate how the sort should happen. Those constants are flag numbers you bitwise combine to quickly, cleanly and efficiently let the sort method know your needs.

---
You can store an entire chessboard in one variable, because there are 64 spaces in a chess board and you can have 64 different single bits in a Number (and each bit is represented by 2, 4, 8, etc...). Even better, you can do cool stuff like:

if (blackHorse & whitePieces) {
   // make black horse take whatever piece is occupying the same space
}


This principle is also known as bitboards, or boards of bits. It's one of the optimizations to make chess AI ultrafast.
---