0

i'm trying to be very precise with the positioning of my bricks when using initBricks. however they are not placing exactly where they should be 9out by small fractions) and i'm pretty certain it is because my code is using ints where i'm trying to get it to use floats. or perhaps the prototype only accepts ints, in which case, how can i get my bricks to be properly spaced given i have to have 10 ROWS and space between the bricks?

/**
 * Initializes window with a grid of bricks.
 */
void initBricks(GWindow window)
{
    float brickWidth = WIDTH / (COLS + 1);
    float brickHeight = HEIGHT / (3*ROWS);
    float brickSpace = WIDTH / (20*(ROWS + 1));

    for (int j = 0; j < ROWS; j++) 
        {
            for (int i = 0; i < COLS; i++)
            {
                GRect brick = newGRect(i*brickWidth + i*brickSpace + brickSpace, j*brickHeight + j*brickSpace + brickSpace,
                                                brickWidth, brickHeight);
                setColor(brick, "RED");
                setFilled(brick, true);
                add(window, brick);
            }
        }
}

2 Answers 2

1

It may just be easier to remember that the coordinates you're passing to the constructor for GRect are pixel coordinates. No matter how precisely you figure what fraction of a pixel should be used,your monitor will only use whole pixels to display an image.

0

If WIDTH, HEIGHT, ROWS, and COLS are integers, then integer division will be performed.

newGRect() accepts doubles.

Assuming x = 0, y = 0, width = 15, height = 10, gap = 5

First row

x = 0
y = 0

the top-left brick should be placed at (0, 0)

x = x + width + gap
  = 0 + 15    + 5  = 20

the next brick should be placed at (20, 0)

x = x  + width + gap
  = 20 + 15    + 5  = 40

the next brick should be placed at (40, 0)

Next row

x = 0
y = y + height + gap
  = 0 + 10     + 5  = 15

the next brick should be placed at (0, 15)

Next row

x = 0
y = y  + height + gap
  = 15 + 10     + 5  = 30

the next brick should be placed at (0, 30)


The previous example in terms of the starting x and y

Assuming starting x = 0, starting y = 0, width = 15, height = 10, gap = 5

First row

x = starting x = 0
y = starting y = 0

the top-left brick should be placed at (0 , 0)

x = starting x + (1 * width) + (1 * gap)
  = 0          + (1 * 15   ) + (1 * 5  ) = 20

the next brick should be placed at (20, 0)

x = starting x  + (2 * width) + (2 * gap)
  = 0           + (2 * 15   ) + (2 * 5  ) = 40

the next brick should be placed at (40, 0)

Next row

x = starting x = 0
y = y + (1 * height) + (1 * gap)
  = 0 + (1 * 10    ) + (1 * 5  ) = 15

the next brick should be placed at (0, 15)

Next row

x = starting x = 0
y = y + (2 * height) + (2 * gap)
  = 0 + (2 * 10    ) + (2 * 5  ) = 30

the next brick should be placed at (0, 30)

floats are NOT precise, better work with ints!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .