patternjavaMinor
Nested loop to render tiles in a grid
Viewed 0 times
gridloopnestedtilesrender
Problem
This code works but I'm not really sure if I wrote it good enough. It seems a bit vague but I can't really assess it properly. I'm particularly concerned with the
xAxis variable. I don't like how I have to initialize it inside the first loop. I would rather have it next to yAxis. Is this a problem?float yAxis = SPACE_BETWEEN_TILES;
float xAxis;
for(int i = 0; i < 3; i++) {
xAxis = SPACE_BETWEEN_TILES;
for(int v = 0; v < 3; v++) {
shapeRenderer.rect(xAxis, yAxis, 10, 10);
xAxis = TILE_WIDTH_AND_HEIGHT + xAxis;
}
yAxis = yAxis + TILE_WIDTH_AND_HEIGHT;
}Solution
I think it is mostly fine as it is. I would declare variables at the level they are actually needed, not before. Also,
You could restructure it like this if you want to:
The performance loss from transforming additions to multiplications should be fine in most cases.
xAxis = TILE_WIDTH_AND_HEIGHT + xAxis; can be written as xAxis += TILE_WIDTH_AND_HEIGHT.i and v are not very good variable names (too short, and they don't fit together). What does v even stand for? vertical? In that case, I would use vertical and horizontal. TILE_WIDTH_AND_HEIGHT would be shorter as TILE_DIMENSION.You could restructure it like this if you want to:
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
shapeRenderer.rect(SPACE_BETWEEN_TILES + TILE_DIMENSION * x, SPACE_BETWEEN_TILES + TILE_DIMENSION * y, 10, 10);
}
}The performance loss from transforming additions to multiplications should be fine in most cases.
Code Snippets
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
shapeRenderer.rect(SPACE_BETWEEN_TILES + TILE_DIMENSION * x, SPACE_BETWEEN_TILES + TILE_DIMENSION * y, 10, 10);
}
}Context
StackExchange Code Review Q#82384, answer score: 7
Revisions (0)
No revisions yet.