# Checkerboard algorithm?

This topic is 1793 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi everyone!

I'm looking to create a function which simulates a checkerboard, i.e. returns 0 for a black square and 1 for a white square. I've got it working for a board where each square has a size of 1, but I can't work out how to make a scaleable version:

//Pseudo-code
checkerboardColour(Vec point)
{
return (floor(p.x) + floor(p.y)) % 2 == 0 ? white : black;
}


I know that I'd need to do a division of some sort to scale the size of the squares, but I can't work out where to put it. Say I wanted to quadruple the size of each black/white square, how would I insert a 'scale' variable into the function to make this happen?

Thanks!

##### Share on other sites

Try this:

//Pseudo-code
checkerboardColour(Vec point, float fScale)
{
return ((int)(p.x/fScale) + (int)(p.y/fScale)) % 2 == 0 ? white : black;
}

##### Share on other sites

Cool, that works :) I actually tried that first but I must have had a bad bracket or something...

##### Share on other sites
Beware of negative numbers.

floor() rounds toward negative infinity, while casting to int rounds toward zero. Depending on how precise you are being with your language, both can be said to round "down".

In this case the two bits of code produce similar, but very different results. One of them will act as though it has a mirror along the axis, the other will be continuous. I'll let you figure out which to help re-enforce the importance.

edit: And since this is talking about the importance of differences is rounding, if you allow the processor to use the floating point round instruction (which is different than casting to int or using floor) then it will use banker's rounding --- that is, rounding toward the nearest even number. In many cases banker's rounding is better because it leads to less numeric drift. When people start talking about rounding to integers, it is best to clarify exactly what they mean; there are many options and each can give dramatically different results. The rounding most of us learned in school is: floor(x+0.5) Edited by frob

• ### What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

• 11
• 13
• 9
• 9
• 15
• ### Forum Statistics

• Total Topics
634078
• Total Posts
3015367
×