This site requires JavaScript, please enable it in your browser!
Greenfoot back
davemib123
davemib123 wrote ...

2013/8/10

use loop to create pattern

davemib123 davemib123

2013/8/10

#
Hi, I am trying to create a pattern with a loop. I have this at the moment but I'm slightly stuck as this displays 9 coins I want 3 displaying:
            for(int i=709 ; i<=846 ; i+=60) {
                 for(int j=113 ; j <= 191 ; j += 36) {
                    addObject(new Coin(), i, j);
                 }
            }
I am trying to form a shape similar to this (diagonal line):
addObject(new Coin(), 709, 191);
addObject(new Coin(), 787, 149);
 addObject(new Coin(), 846, 113);
danpost danpost

2013/8/10

#
Using the values in your first code snippet above:
for (int i=0; i<3; i++)
{
    addObject(new Coin(), 709+i*60, 113+i*36);
}
davemib123 davemib123

2013/8/11

#
Thanks for that Danpost.
danpost danpost

2013/8/11

#
If the initial value of i in line 16 was supposed to be 552 instead of 522 (like in line 13), then it would be possible to perform a double for loop (one inside the other) to produce this pattern:
for (int i=0; i<6; i++) for (j=0; j<i+1; j++) addObject(new Coin(), 552-30*j, 360+30*i);
NOTE: this post was in response to the original text of the previous post (which was changed) by davemib123 which involved a question of better code than multiple for loops to create a pattern of coin objects.
davemib123 davemib123

2013/8/11

#
yea sorry about that, I made it using rectangular shapes so edited the post. but your version is so much better :)
You need to login to post a reply.