【问题标题】:Formula to draw pyramid of circles绘制圆金字塔的公式
【发布时间】:2010-06-14 02:33:34
【问题描述】:

我正在尝试为我的游戏创建一个圆形金字塔,看起来类似于:

alt text http://img266.imageshack.us/img266/3094/lab1213c.jpg

但我无法正确打印。我不断地得到非常奇怪的螺旋,但没有什么接近于此。谁能给我一些正确配方的提示?我的窗口是 600x600,金字塔的底是 8。

    fields = new Field[BASE*(BASE/2)+4];
    int line_count = BASE;
    int line_tmp = line_count;
    for(int i=0; i< fields.length; i++){
        for( int j=line_tmp; j <= line_count; j++){
            fields[i] = new Field(0, (150+(line_tmp*5)),(600+line_tmp*5));
        }
        line_count--;
        line_tmp = line_count;
    }

【问题讨论】:

  • 在我看来更像三角形而不是金字塔
  • 一方面,您没有在其 for 循环内的任何地方引用 j。您多次重新分配给字段[i]。
  • 也许还有一些关于Field() 参数的信息会有所帮助。另外,您是在尝试使用一维数组还是二维数组来存储字段?
  • 1D。你所看到的就是当前的一切。 Base = 8,它是这个“三角形”、“金字塔”的底

标签: java drawing formula


【解决方案1】:

我看到的错误是:

  • 数组大小公式不正确。
  • 在您的 y 表达式中包含 line_tmp(这似乎是您的列计数器)。
  • 有两个变量,line_countline_temp,它们总是相等的。
  • 让您的外循环按节点计数,而不是按行计数。
  • 到处都是无意义的变量名和神奇的数字。
// I use java.util.ArrayList because using its add(..) method is convenient here.
// The proper forumula for anticipated number of nodes is: base×(base+1)÷2
final List<Field> fields = new ArrayList<Field>(BASE*(BASE+1)/2);
// I use a java.awt.Point to store the (x,y) value of the first node of the row.
// This clarifies the meaning, rather than using ints or long inline expressions.
final Point rowStart = new Point(PANEL_WIDTH/2, DIAMETER);

// The number of rows equals the number of nodes on the final row.
for (int row = 1; row <= BASE; row++) {
    // The nth row has n nodes.
    for (int circle = 0; circle < row; circle++) {
        // Each row starts at rowStart and each subsequent circle is offset to 
        // the right by two times the circle diameter.
        fields.add(new Field(0, rowStart.x + circle*DIAMETER*2, rowStart.y));
    }
    // Each subsequent row starts a little down and to the left of the previous.
    rowStart.x -= DIAMETER;
    rowStart.y += DIAMETER;
}

如果这是家庭作业,请记住仅将其用作修复您自己的代码的参考。

【讨论】:

  • +1 - 另一个问题是 OP 忽略了表达式中局部变量名称和空格的公认 Java 样式约定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多