Drawing a checker board pattern quickly with AS3

Today I needed to dynamically generate a checker board pattern in ActionScript 3. I couldn’t find any examples on how to do it so I made my own. Below is a snippet of code I wrote to draw it and its super fast! I used bitwise operators in the loops to speed it up and it can draw a 2000x2000px area in 10 milliseconds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Box colour 1
var even:uint = 0xCCCCCC;

// Box colour 2
var odd:uint = 0x999999;

// Box size
var size:int = 10;

// number of boxes horizontally
var nH:int = stage.stageWidth / size;

// number of boxes vertically
var nV:int = stage.stageHeight / size;

// vars to be used in the loops
var clr:uint;
var i:uint;
var j:uint;

// loop vertical
for (i=0;i<nV;++i)
{
    // Flip values of Even and Odd colours using Bitwise operations
    even ^= odd;
    odd  ^= even;
    even ^= odd;
   
    // loop horizontal
    for (j=0;j<nH;++j)
    {
        //bitwise modulus
        //check if column is odd or even, then set colour
        clr = j & 1 ? even : odd;
       
        // draw box with previously set colour
        graphics.beginFill(clr,1);
        graphics.drawRect(Number(j*size),Number(i*size),size,size);
        graphics.endFill();
    }
}
Posted toActionScript Flash