我试图使用C和斯坦福便携式库(SPL)重新创建破砖者。我的initBricks函数的目标是在每行中添加5行ROWS和10个COLUMNS(总共50块砖)。当我运行此代码时,我的窗口只有10个砖的1行。由于某种原因,它不会输出其他4行。我的代码中没有看到我出错的地方。在创建每一行之后,我将y坐标(0,0是窗口的左上角)递增40。
// number of rows of bricks
#define ROWS 5
// number of columns of bricks
#define COLS 10
// height and width of bricks
#define BRICK_H 7.5
#define BRICK_W 35
// initializes window with grid of bricks
void initBricks(GWindow window)
{
// set initial brick coordinates
int x_coord = 2;
int y_coord = 10;
for (int i = 0; i < ROWS; i++)
{
// Create 10 columns of bricks
for (int j = 0; j < COLS; j++)
{
// create a brick
GRect brick = newGRect(x_coord, y_coord, BRICK_W, BRICK_H);
setFilled(brick, true);
setColor(brick, "RED");
add(window, brick);
// increment x coordinate for column spacing
x_coord += 40;
}
// increment y coordinate for row spacing
y_coord += 40;
}
}
非常感谢任何帮助!
答案 0 :(得分:2)
您需要重置每行的X坐标。
for (int i = 0; i < ROWS; i++)
{
// Create 10 columns of bricks
int x_coord = 2; // <---- move line down to here
for (int j = 0; j < COLS; j++)
{
...
答案 1 :(得分:2)
您不能在外部for循环中重置x_coord
变量,因此在第一行的末尾,您的x_coord
为202,并且它开始编写下一行可能在窗外。只需在x_coord = 2;
之后添加y_coord += 40;
即可修复它。
for (int i = 0; i < ROWS; i++)
{
for (int j = 0; j < COLS; j++)
{
// create a brick
GRect brick = newGRect(x_coord, y_coord, BRICK_W, BRICK_H);
setFilled(brick, true);
setColor(brick, "RED");
add(window, brick);
// increment x coordinate for column spacing
x_coord += 40;
}
// increment y coordinate for row spacing
y_coord += 40;
//reset c coordinate
x_coord = 2;
}
答案 2 :(得分:1)
如前所述,问题是X坐标。您可以通过将X,Y计算移动到for
循环
void initBricks(GWindow window)
{
int row, col, x, y;
for ( y = 10, row = 0; row < ROWS; row++, y += 40 )
for ( x = 2, col = 0; col < COLS; col++, x += 40 )
{
GRect brick = newGRect(x, y, BRICK_W, BRICK_H);
setFilled(brick, true);
setColor(brick, "RED");
add(window, brick);
}
}
答案 3 :(得分:0)
你应该在外循环体中初始化y坐标。 因为每当你到达下一行时y坐标想要回到它的初始位置。
// number of rows of bricks
#define ROWS 5
// number of columns of bricks
#define COLS 10
// height and width of bricks
#define BRICK_H 7.5
#define BRICK_W 35
// initializes window with grid of bricks
void initBricks(GWindow window)
{
// set initial brick coordinates
int x_coord = 2;
for (int i = 0; i < ROWS; i++)
{
int y_coord = 10;
// Create 10 columns of bricks
for (int j = 0; j < COLS; j++)
{
// create a brick
GRect brick = newGRect(x_coord, y_coord, BRICK_W, BRICK_H);
setFilled(brick, true);
setColor(brick, "RED");
add(window, brick);
// increment x coordinate for column spacing
x_coord += 40;
}
// increment y coordinate for row spacing
y_coord += 40;
}
}