Create a chess/checker board with for loop?

This code create a checker board style grid, I just wonder if there’s a better way to set the colors or create this style of pattern?

    local group = display.newGroup()      local blocks = {}      local blockSize = display.contentWidth/5     for i = 1, 5, 1 do         for j = 1, 5, 1 do                          blocks[i] = display.newRect(group,  0, 0, blockSize, blockSize)             blocks[i]:setReferencePoint(display.CenterReferencePoint)             blocks[i].x = ((blockSize/2) + (i-1) \* blockSize)             blocks[i].y = (100 +(j-1) \* blockSize)             blocks[i]:setFillColor(0, 0, 0, 255)               if (i == 1) and ( j == 1) or (i == 1) and (j == 3) or (i == 1) and (j == 5)  then             blocks[i]:setFillColor(255, 255, 255, 255)             end               if (i == 2) and ( j == 2) or (i == 2) and (j == 4) then             blocks[i]:setFillColor(255, 255, 255, 255)             end               if (i == 3) and ( j == 1) or (i == 3) and (j == 3) or (i == 3) and (j == 5)  then             blocks[i]:setFillColor(255, 255, 255, 255)             end               if (i == 4) and ( j == 2) or (i == 4) and (j == 4) then             blocks[i]:setFillColor(255, 255, 255, 255)             end               if (i == 5) and ( j == 1) or (i == 5) and (j == 3) or (i == 5) and (j == 5)  then             blocks[i]:setFillColor(255, 255, 255, 255)             end         end     end

Hi Cindy,

Yes, the better way would be to do it like this:

[lua]

blocks[i]:setFillColor(0, 0, 0, 255)

if (i+j)%2 == 0 then

   blocks[i]:setFillColor(255, 255, 255, 255)

end

[/lua]

The expression (i+j)%2 uses the % (modulo operator, which gives you the remainder after dividing.  So (i+j)%2==0 tests whether (i+j) is divisible by 2 (remainder is 0).

  • Andrew

Hi Cindy,

Yes, the better way would be to do it like this:

[lua]

blocks[i]:setFillColor(0, 0, 0, 255)

if (i+j)%2 == 0 then

   blocks[i]:setFillColor(255, 255, 255, 255)

end

[/lua]

The expression (i+j)%2 uses the % (modulo operator, which gives you the remainder after dividing.  So (i+j)%2==0 tests whether (i+j) is divisible by 2 (remainder is 0).

  • Andrew