2

I'm trying to create a pyramid of circles to my game, looking similar to this :

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

But I can't make it print properly. Constantly I'm getting really strange spirals but nothing close to this. Can anyone give me some tip on proper formula ? My window is 600x600, base of pyramid is 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;
    }
terence6
  • 151
  • 2
  • 2
  • 11
  • Looks more like a triangle than a pyramid to me – Artelius Jun 14 '10 at 02:41
  • For one thing, you're not referencing j anywhere inside its for loop. You reassign to fields[i] multiple times. – Adam Crume Jun 14 '10 at 02:51
  • Perhaps also a bit of information about the parameters to `Field()` would help. Also, are you trying to use a 1D or a 2D array to store the fields? – a_m0d Jun 14 '10 at 03:32
  • 1D. What you see is everything currently. Base = 8, it's the base of this 'triangle' , 'pyramid' whatever – terence6 Jun 14 '10 at 03:34

1 Answers1

2

The mistakes I see are:

  • Incorrect array size formula.
  • Including line_tmp (which seems to be your column counter) in your y expression.
  • Having two variables, line_count and line_temp that are always equal.
  • Having your outer loop count by node rather than counting by row.
  • Having generally meaningless variable names and magic numbers strewn about.
// 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;
}

Remember to only use this as reference for fixing your own code if this is homework.

Gunslinger47
  • 7,001
  • 2
  • 21
  • 29
  • +1 - Another problem is the OP is ignoring accepted Java style conventions for local variable names and spaces in expressions. – Stephen C Jun 14 '10 at 05:37