Monday, January 20, 2014

Breakout Blocks

I spent about 3 hours on Saturday working on a Java program to set up a breakout game. The programming went really smoothly. I'm really liking Java. I'm especially proud of this little bit of code inside nested for loops, though I'm not sure that it's good code:

//Decide fill color based on position
brick.setFillColor(Color.RED); //We know the first two rows should be this color, so no need to check which row right away. Also, this makes it default back to red if more rows are added later or something goes wrong.


if(rows == 2 || rows == 3) brick.setFillColor(Color.ORANGE);
if(rows == 4 || rows == 5) brick.setFillColor(Color.YELLOW);
if(rows == 6 || rows == 7) brick.setFillColor(Color.GREEN);
if(rows == 8 || rows == 9) brick.setFillColor(Color.CYAN);

On the one hand, there's no reason to check if rows is between 0 and 1 because that's where it starts so we can just assign it. On the other hand, it means for everything else it gets assigned twice. Which is cheaper, if statements like this or assignment?

No comments:

Post a Comment