Programming with GreenfootÉtudes — Chapter 5

The following exercises are intended to be implemented in the Greenfoot scenario "space". Download the scenario here and open it in Greenfoot before continuing.

Writing some loops

1. Open the Space class. Modify the constructor so that it paints 300 stars.

Use a loop to achieve this. You can paint a star by painting a very small (one or two pixel) circle on the background image. Study the existing code to see how to paint onto the background. Then consult the documentation for the GreenfootImage class to find out how to paint a circle.

You may like to start by initially drawing just one single star. Then extend your code to include a loop to paint all the stars. Make sure to write the star-painting code in a separate method, not in the constructor directly.

2. Add code to the Space class so that 5 Asteroids are automatically placed into the world at random locations. Use a loop to achieve this. Write the code that creates the asteroids in a separet private method.

Back to Études page