我正在努力解决的问题是在用单独砖块建造的窗口中建立一个金字塔。随着代码的打击,我预计第一排应该有1块砖,第2排有2块砖,第3排有3块,金字塔底部有12块砖。相反,屏幕中央只出现1块砖。我该怎么做才能纠正我的代码?
import acm.program.*;
import acm.graphics.*;
public class BrickPyramid extends GraphicsProgram{
public void run() {
/** xBrick, yBrick trying to calculate for the center of the window **/
double xBrick = (getWidth() - BRICK_WIDTH) / 2 ;
double yBrick = (getHeight() - BRICK_HEIGHT) /2 ;
/** getting the size of the brick by multiplying the brick width by brick height **/
double buildingBrick = BRICK_WIDTH * BRICK_HEIGHT;
for (int i = 0 ; i <= 12; i ++ ){
for (int j = 0; j < BRICKS_IN_BASE; j++){
double x = i * buildingBrick;
double y = j * buildingBrick;
/* adding the brick with starting point xbrick, ybrick **/
GRect brick = new GRect (xBrick, yBrick, BRICK_WIDTH, BRICK_HEIGHT);
add(brick);
}
}
}
private static final int BRICK_WIDTH = 100;
private static final int BRICK_HEIGHT = 50;
private static final int BRICKS_IN_BASE = 12;
}
答案 0 :(得分:2)
你用这条线执行多次构建你的所有砖块:
GRect brick = new GRect (xBrick, yBrick, BRICK_WIDTH, BRICK_HEIGHT);
但是你永远不会改变传递给构造函数的任何变量的值,所以砖块都被绘制在同一个地方。
您需要为每个砖更改这些值。也许使用i和j来确定这些值?
答案 1 :(得分:0)
不知道你是否还在寻找答案,但是这段代码完成了这项工作:
公共类Pyramid扩展了GraphicsProgram {
private static final int BRICK_WIDTH = 30;
private static final int BRICK_HEIGHT = 12;
public void run() {
double xBrick = (getWidth() - BRICK_WIDTH) / 2 ;
double yBrick = (getHeight() - BRICK_HEIGHT) /2 ;
for (int n=1;n<15;n++){
for (int m=0;m<=n-1;m++){
GRect Brick =new GRect(xBrick-(BRICK_WIDTH*(n-1))/2+m*BRICK_WIDTH,yBrick+BRICK_HEIGHT*(n-1),BRICK_WIDTH,BRICK_HEIGHT);
add(Brick);
}
}
}
}