(SIPC) Loops Lesson

Loops

A programming construct we have not discussed so far is a loop. Loops are called iteration. The code is repeated multiple times creating a loop. Games have a main game loop that keeps the game running. In Greenfoot, the game loop is the act method. The act method will run over and over again in a loop.  

Action games probably require more conditionals than loops. Loops are helpful if you have multiple objects to instantiate, if you to animate an image, or if you want an action inside a method repeated.  

The Explosion class uses a for loop to animate the explosion image.  

Examine the code below.

Field Data  

  • A variable is created to store the number of images for the animation. IMAGE_COUNT
  • Next the array is created to store the images.
  • Variables are created to store the size of the explosion and an increment to make it increase in size.

Constructor:

  • The image is set to the initial image and the intialiseImages() method is called.  

code block:
/** How many images should be used in the animation of the explostion */ private final static int IMAGE_COUNT= 8;
The images in the explosion. This is static so the images are not
ā†’ recreated for every object (improves performance significantly).
private static Greenfoot Image [] images;
/** Current size of the explosion */ private int imageNo = 0;
/** How much do we increment the index in the explosion animation. */ private int increment=1;
public Explosion () {
initialise Images();
setImage (images [0]);
Greenfoot.playSound ("Explosion.wav");

initialiseImages() method

The method starts out with an if statement to see if the images is null. If so, it sets the image to the explosion.png. The maximum size is calculated and delta. The images array is initialized to IMAGE_COUNT.

The for loop will start at 0 and loop until i is less than IMAGECOUNT. As it loops, the size is created so it will increase each time through the loop. The first image at index 0 is set to the explosion.png (baseImage). It scales the image and the loop continues until it is less than IMAGE_COUNT.

code block:
public synchronized static void initialise Images () {
if (images = null) {
Greenfoot Image base Image = new Greenfoot Image ("explosion.png");
int maxSize = baseImage.getWidth()/2;
int delta = maxsize (IMAGE_COUNT+1);
int size = 0;
images = new Greenfoot Image [IMAGE_COUNT];
for (int i=0; i< IMAGE_COUNT; i++) {
size size + delta;
images [i]= new Greenfoot Image (baseImage);
images[i].scale(size, size);

[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION