(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.
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.
[CC BY 4.0] UNLESS OTHERWISE NOTED | IMAGES: LICENSED AND USED ACCORDING TO TERMS OF SUBSCRIPTION