Open the project space in greenfoot and study the codes of the classes Space and Asteroid.
2. Modify the constructor so that the space world paints 300 stars. To paint a star you write the following code:
GreenfootImage star = getBackground(); star.setColor(Color.WHITE); star.drawOval(50,50,2,2);
this will draw a small white star at location (50,50) with dimensions 2x2.
Draw 300 stars with the same dimensions but at random locations. Make sure the stars are drawn when the world starts.
Make sure you write your code in a separate method drawStars().
3. 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 separate private method drawAsteroids().
public class Space extends World
{
public Space()
{
super(600, 400, 1);
GreenfootImage background = getBackground();
background.setColor(Color.BLACK);
background.fill();
GreenfootImage star = getBackground();
star.setColor(Color.WHITE);
star.drawOval(50,50,2,2);
drawStars(300);
drawAsteroids(5);
}
private void drawStars(int numberOfStars)
{
GreenfootImage bg = getBackground();
bg.setColor(Color. WHITE);
for (int i = 0; i < numberOfStars; i++) {
int x = Greenfoot.getRandomNumber( getWidth() );
int y = Greenfoot.getRandomNumber( getHeight() );
bg.fillOval(x, y, 1, 1);
}
}
private void drawAsteroids(int numberOfAsteroids) {
for (int i = 0; i < numberOfAsteroids; i++) {
int x = Greenfoot.getRandomNumber( getWidth() );
int y = Greenfoot.getRandomNumber( getHeight() );
}
}
}