0

我要解决的问题是在用单独的砖块建造的窗口中建造一个金字塔。通过代码打击,我希望第一排应该有 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;
}
4

2 回答 2

2

您使用此行多次执行构建所有砖块:

GRect brick = new GRect (xBrick, yBrick, BRICK_WIDTH, BRICK_HEIGHT);

但是您永远不会更改传递给构造函数的任何变量的值,因此砖块都绘制在同一个地方。

您需要为每个积木更改这些值。也许使用 i 和 j 来确定这些值?

于 2012-11-22T01:01:33.353 回答
0

不知道您是否仍在寻找答案,但这段代码可以完成工作:

公共类 Pyramid 扩展 GraphicsProgram {

私有静态最终 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);

        }
      }
}

}

于 2014-11-24T08:51:03.217 回答