Return to Snippet

Revision: 39604
at January 19, 2011 02:19 by joswald


Initial Code
import greenfoot.*;  // (Actor, World, Greenfoot, GreenfootImage)

public class CrabWorld extends World
{
    private static final int STARTING_X = 150;
    private static final int STARTING_Y = 100;
    private static final int NUMBER_OF_WORMS = 5;
    private static final int NUMBER_OF_LOBSTERS = 3;
    private static final int WORLD_X = 800;
    private static final int WORLD_Y = 800;

    /**
     * Create the default crab world (the beach). Our world has a size 
     * of 800x800 cells, where every cell is just 1 pixel, five worms
     * and three lobsters
     */
    public CrabWorld() 
    {
        super(WORLD_X, WORLD_Y, 1);        
        populate( STARTING_X, STARTING_Y, NUMBER_OF_WORMS, NUMBER_OF_LOBSTERS );
    }
    
    /**
     * Fully parameterized version of the CrabWorld constructor. 
     * Specify the width and height of the world, the starting location of the crab,
     * and the number of worms and lobsters. 
     * 
     * @param width the width of the world in cells (pixels, effectively)
     * @param height the height of the world in cells (pixels, effectively)
     * @param startX the starting x-coordinate of the crab
     * @param startY the starting y-coordinate of the crab
     * @param numberOfWorms the starting number of worms
     * @param numberOfLobsters the starting number of lobsters
     */
    public CrabWorld( int width, int height, int startX, int startY, int numberOfWorms, int numberOfLobsters )
    {
        super( width, height, 1 );
        populate( startX, startY, numberOfWorms, numberOfLobsters);
    }
    
    /**
     * Partially paramterized version of the CrabWorld constructor.
     * Specify the number of worms and lobsters only. 
     * 
     * @param numberOfWorms the starting number of worms
     * @param numberOfLobsters the starting number of lobsters 
     */
    public CrabWorld( int numberOfWorms, int numberOfLobsters )
    {
        super(WORLD_X, WORLD_Y, 1);        
        populate( STARTING_X, STARTING_Y, numberOfWorms, numberOfLobsters);
    }    
    
    private void populate( int startX, int startY, int worms, int lobsters )
    {
        addObject( new Crab(), startX, startY );
        
        for( int i = 0; i < worms; i++ )
        {
            addObject( new Worm(), Greenfoot.getRandomNumber( getWidth() ), Greenfoot.getRandomNumber( getHeight() ) );
        }
        
        for( int i = 0; i < NUMBER_OF_LOBSTERS; i++ )
        {
            addObject( new Lobster(), Greenfoot.getRandomNumber( getWidth() ), Greenfoot.getRandomNumber( getHeight() ) );
        }        
    }
    
    
}

Initial URL

                                

Initial Description
A much better implementation of the parameterized and randomized CrabWorld

Initial Title
CrabWorld with Parameterized and Random Object Placement

Initial Tags
java

Initial Language
Java