如何使用嵌套for循环构建砖金字塔

时间:2012-11-25 09:47:50

标签: java

我正在解决一个问题,我遇到了很多麻烦。问题的概念是使用砖块建造金字塔。整个金字塔的砖块都在窗户中央。我可以绘制一块砖,然后是两块,然后是三层,直到12层,构成金字塔的底部,但是所有的砖块都在窗口左边的左边缘上,而不是在窗口中心。

使用getWidth()和getHeight()我可以做(getWidth() - BRICK_WIDTH)/ 2;获得砖的x坐标的中心。然后(getHeight() - BRICK_HEIGHT)/ 2;对于一块砖的y坐标的中心。唯一的问题是我不知道在哪里输入该代码,因此它适用于所有砖块,因此每排砖块都在窗口中居中。

import acm.program.*;
import acm.graphics.*;

public class Pyramid extends GraphicsProgram {
  public void run() {
    double xCoordinate = (getWidth() - BRICKWIDTH) / 2;
    double yCoordinate = (getHeight() - BRICK_HEIGHT / 2);
    for (int i = 0; i < BRICKS_IN_BASE; i++) {
      for (int j = 0; j < i; j++) {
        double x = j * BRICK_WIDTH;
        double y = i * BRICK_HEIGHT;
        GRect square = new GRect(x, y, BRICK_WIDTH, BRICK_HEIGHT);
        add(square);
      }
    }
  }
  private static final int BRICK_WIDTH = 50;
  private static final int BRICK_HEIGHT = 25;
  private static final int BRICKS_IN_BASE = 12;
}

2 个答案:

答案 0 :(得分:0)

你的意思是什么?

    double x = xCoordinate + j * BRICK_WIDTH;
    double y = yCoordinate + i * BRICK_HEIGHT;

答案 1 :(得分:0)

你应该尝试这样的事情:

import acm.program.*;
import acm.graphics.*;

public class Pyramid extends GraphicsProgram
{
    public void run()
    {
        // We calculate some values in order to center the pyramid vertically
        int pyramidHeight = BRICKS_IN_BASE * BRICK_HEIGHT;
        double pyramidY = (getHeight() - pyramidHeight) / 2;

        // For each brick layer...
        for (int i=BRICKS_IN_BASE ; i >= 1; i--)
        {
            // We calculate some values in order to center the layer horizontally
            int layerWidth = BRICKWIDTH * i;
            double layerX = (getWidth() - layerWidth) / 2;
            double layerY = pyramidY + (i-1) * BRICK_HEIGHT;

            // For each brick in the layer...
            for(int j=0 ; j<i ; j++)
            {
                GRect square = new GRect(layerX + j*BRICK_WIDTH, layerY, BRICK_WIDTH, BRICK_HEIGHT);
                add(square);
            }
        }
    }

    private static final int BRICK_WIDTH = 50;
    private static final int BRICK_HEIGHT = 25;
    private static final int BRICKS_IN_BASE = 12;
}

在这个实现中,我们首先计算图层的全局宽度(因为我们已经知道它将有多少砖),我们用它来找到图层的全局“起点”,我们从中找到所有矩形的所有坐标。