MY CODE >> Asteroids
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)
import java.awt.Color;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import java.util.ArrayList;

import com.mysql.jdbc.*;
import java.sql.DriverManager;
import java.sql.ResultSet;

/**
 * Space. Something for rockets to fly in.
 * Modified code from the Capella IT Lab (Dec. 2010) based on
 * @author Michael Kolling
 * @version 1.1
 */
public class Space extends World
{
     private Counter scoreCounter;
     private int startAsteroids = 3;
     private String player;
     private ArrayList topTen;

     private Connection conn;
     private PreparedStatement stmt;
     private static String SERVER_ADDR = "vle8.capella.edu";
     private static String USER_NAME = "tm1296948";   // Change to your DB user name
     private static String PASSWORD = "tm1296948tm";    // Change to your DB password
     private static String DATABASE_URL = "jdbc:mysql://" + SERVER_ADDR + "/" + USER_NAME;

     public Space()
     {
          super(600, 400, 1);
          GreenfootImage background = getBackground();
          background.setColor(Color.BLACK);
          background.fill();
          createStars(300);

          Rocket rocket = new Rocket();
          addObject(rocket, getWidth()/2 + 100, getHeight()/2);

          addAsteroids(startAsteroids);

          scoreCounter = new Counter("Score: ");
          addObject(scoreCounter, 60, 380);

          Explosion.initializeImages();
          ProtonWave.initializeImages();

          topTen = new ArrayList();
     }

     /**
      * Add a given number of asteroids to our world. Asteroids are only added into
      * the left half of the world.
      */
     private void addAsteroids(int count)
     {
          for(int i = 0; i < count; i++)
          {
               int x = Greenfoot.getRandomNumber(getWidth()/2);
               int y = Greenfoot.getRandomNumber(getHeight()/2);
               addObject(new Asteroid(), x, y);
          }
     }

     /**
      * Create a given number of stars in space.
      */
     private void createStars(int number)
     {
          GreenfootImage background = getBackground();
          for(int i=0; i < number; i++)
          {
               int x = Greenfoot.getRandomNumber( getWidth() );
               int y = Greenfoot.getRandomNumber( getHeight() );
               int color = 120 - Greenfoot.getRandomNumber(100);
               background.setColor(new Color(color,color,color));
               background.fillOval(x, y, 2, 2);
          }
     }

     public void changeScore(int pts) {
          scoreCounter.add(pts);
     }

     /**
      * This method is called when the game is over to display the final score, save to the DB, and display top 10 scores.
      */
     public void gameOver()
     {
          try {
               connectToDB();
               saveScore();
               getTopTen();
          }
          catch (Exception ex) {
               System.out.println(ex.getMessage());
          }
          finally {
               addObject(new ScoreBoard(scoreCounter.getValue(), topTen), getWidth()/2, getHeight()/2);
          }
     }

     private void connectToDB() throws Exception
     {
          Class.forName("com.mysql.jdbc.Driver");
          conn = (Connection) DriverManager.getConnection(DATABASE_URL, USER_NAME, PASSWORD);
     }

     private void saveScore() throws Exception
     {
          SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
          String InsertSQL = "INSERT INTO scores(player, score, gamedate) VALUES(?, ?, ?)";
          stmt = (PreparedStatement) conn.prepareStatement(InsertSQL);
          stmt.setString(1, player);
          stmt.setInt(2, scoreCounter.getValue());
          String dateTime = format.format(Calendar.getInstance().getTime());
          stmt.setString(3, dateTime);
          stmt.executeUpdate();
     }

     private void getTopTen() throws Exception
     {
          String Top10SQL = "SELECT * FROM scores ORDER BY score DESC LIMIT 10";
          ResultSet rs = stmt.executeQuery(Top10SQL);
          topTen = new ArrayList();
          while(rs.next()) {
               topTen.add(rs.getInt("score") + " - " + rs.getString("player") + " - " + rs.getString("gamedate"));
          }
          conn.close();
     }

     public void setPlayerName(String playerName) {
        player = playerName;
     }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)
import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;

/**
 * The ScoreBoard is used to display results on the screen. It can display some
 * text and several numbers.
 *
 * @author M Kolling
 * @version 1.0
 */
public class ScoreBoard extends Actor
{
     public static final float FONT_SIZE = 18.0f;
     public static final int WIDTH = 450;
     public static final int HEIGHT = 380;

     /**
      * Create a score board with dummy result for testing.
      */
     public ScoreBoard()
     {
          this(100);
     }

     /**
      * Create a score board for the final result.
      */
     public ScoreBoard(int score)
     {
          makeImage("Game Over", "Score: ", score, null);
     }

     public ScoreBoard(int score, ArrayList top10)
     {
          makeImage("Game Over", "Score: ", score, top10);
     }

     /**
      * Make the score board image.
      */
     private void makeImage(String title, String prefix, int score, ArrayList top10)
     {
          GreenfootImage image = new GreenfootImage(WIDTH, HEIGHT);
          image.setColor(new Color(255,255,255, 128));
          image.fillRect(0, 0, WIDTH, HEIGHT);
          image.setColor(new Color(0, 0, 0, 128));
          image.fillRect(5, 5, WIDTH-10, HEIGHT-10);
          Font font = image.getFont();
          font = font.deriveFont(FONT_SIZE);
          image.setFont(font);
          image.setColor(Color.WHITE);
          image.drawString(title, 20, 30);
          image.drawString(prefix + score, 20, 50);
          image.drawString("Top 10 Scores", 20, 110);
          for(int i = 0; i < top10.size(); i++)
          {
               image.drawString(top10.get(i), 20, 140 + i * 25);
          }
          setImage(image);
     }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)
import java.util.List;

/**
 * A proton wave that expands and destroys things in its path.
 * 
 * @author Michael Kolling
 * @version 1.0
 */
public class ProtonWave extends Actor
{
    /** The damage this wave will deal */
    private static final int DAMAGE = 30;
    
    /** How many images should be used in the animation of the wave */
    private static final int NUMBER_IMAGES= 30;
    
    /** 
     * The images of the wave. This is static so the images are not
     * recreated for every object (improves performance significantly).
     */
    private static GreenfootImage[] images;
    
    /** Current size of the wave */
    private int imageCount = 0;
    
    /**
     * Create a new proton wave.
     */
    public ProtonWave() 
    {
        initializeImages();
        setImage(images[0]);
        Greenfoot.playSound("proton.wav");
    }
    
    /** 
     * Create the images for expanding the wave.
     */
    public static void initializeImages() 
    {
        if (images == null) 
        {
            GreenfootImage baseImage = new GreenfootImage("wave.png");
            images = new GreenfootImage[NUMBER_IMAGES];
            for (int i = 0; i < NUMBER_IMAGES; i++) 
            {
                int size = (i+1) * ( baseImage.getWidth() / NUMBER_IMAGES );
                images[i] = new GreenfootImage(baseImage);
                images[i].scale(size, size);
            }
        }
    }
    
    /**
     * Act for the proton wave is: grow and check whether we hit anything.
     */
    public void act()
    { 
        checkCollision();
        grow();
    }
    
    /**
     * Explode all intersecting asteroids.
     */
    private void checkCollision()
    {
        int range = getImage().getWidth() / 2;
        List asteroids = getObjectsInRange(range, Asteroid.class);     
        
        for (Asteroid a : asteroids) {
            a.hit (DAMAGE);
        }
    }

    /**
     * Grow this wave. If we get to full size, remove.
     */
    private void grow()
    {
        if (imageCount >= NUMBER_IMAGES) 
        {
            getWorld().removeObject(this);
        }
        else 
        {
            setImage(images[imageCount]);
            imageCount++;
        }
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

import java.awt.Color;
import java.awt.Graphics;

/**
 * Counter that displays a text and number.
 * 
 * @author Michael Kolling
 * @version 1.0.1
 */
public class Counter extends Actor
{
    private static final Color textColor = new Color(255, 180, 150);
    
    private int value = 0;
    private int target = 0;
    private String text;
    private int stringLength;

    public Counter()
    {
        this("");
    }

    public Counter(String prefix)
    {
        text = prefix;
        stringLength = (text.length() + 2) * 10;

        setImage(new GreenfootImage(stringLength, 16));
        GreenfootImage image = getImage();
        image.setColor(textColor);

        updateImage();
    }
    
    public void act() {
        if(value < target) {
            value++;
            updateImage();
        }
        else if(value > target) {
            value--;
            updateImage();
        }
    }

    public void add(int score)
    {
        target += score;
    }

    public int getValue()
    {
        return value;
    }

    /**
     * Make the image
     */
    private void updateImage()
    {
        GreenfootImage image = getImage();
        image.clear();
        image.drawString(text + value, 1, 12);
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

/**
 * An explosion. It starts by expanding and then collapsing. 
 * The explosion will explode other obejcts that the explosion intersects.
 * 
 * @author Poul Henriksen
 * @version 1.0.1
 */
public class Explosion extends Actor
{
    /** How many images should be used in the animation of the explostion */
    private final static int IMAGE_COUNT= 12;
    
    /** 
     * The images in the explosion. This is static so the images are not
     * recreated for every object (improves performance significantly).
     */
    private static GreenfootImage[] 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;
    
    /**
     * Create a new explosion.
     */
    public Explosion() 
    {
        initializeImages();
        setImage(images[0]);
        Greenfoot.playSound("MetalExplosion.wav");
    }    
    
    /** 
     * Create the images for explosion.
     */
    public synchronized static void initializeImages() 
    {
        if(images == null) {
            GreenfootImage baseImage = new GreenfootImage("explosion-big.png");
            images = new GreenfootImage[IMAGE_COUNT];
            for (int i = 0; i < IMAGE_COUNT; i++)
            {
                int size = (i+1) * ( baseImage.getWidth() / IMAGE_COUNT );
                images[i] = new GreenfootImage(baseImage);
                images[i].scale(size, size);
            }
        }
    }
    
    /**
     * Explode!
     */
    public void act()
    { 
        setImage(images[imageNo]);

        imageNo += increment;
        if(imageNo >= IMAGE_COUNT) {
            increment = -increment;
            imageNo += increment;
        }
        
        if(imageNo < 0) {
            getWorld().removeObject(this);
        }
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

/**
 * A variation of an actor that maintains precise location (using doubles for the co-ordinates
 * instead of ints). It also maintains a current movement in form of a movement vector.
 * 
 * This is a variation of the SmoothMover class presented ealier in the book (version 2.0).
 * This version implements wrap-around movement: when the actor moves out of the world at one
 * side, it enters it again at the opposite edge.
 * 
 * @author Poul Henriksen
 * @author Michael Kolling
 * 
 * @version 2.1
 */
public abstract class SmoothMover extends Actor
{
    private Vector movement;
    private double exactX;
    private double exactY;
    
    public SmoothMover()
    {
        this(new Vector());
    }
    
    /**
     * Create new thing initialised with given speed.
     */
    public SmoothMover(Vector movement)
    {
        this.movement = movement;
    }
    
    /**
     * Move in the current movement direction. Wrap around to the opposite edge of the
     * screen if moving out of the world.
     */
    public void move() 
    {
        exactX = exactX + movement.getX();
        exactY = exactY + movement.getY();
        if(exactX >= getWorld().getWidth()) {
            exactX = 0;
        }
        if(exactX < 0) {
            exactX = getWorld().getWidth() - 1;
        }
        if(exactY >= getWorld().getHeight()) {
            exactY = 0;
        }
        if(exactY < 0) {
            exactY = getWorld().getHeight() - 1;
        }
        super.setLocation((int) exactX, (int) exactY);
    }
    
    /**
     * Set the location from exact coordinates.
     */
    public void setLocation(double x, double y) 
    {
        exactX = x;
        exactY = y;
        super.setLocation((int) x, (int) y);
    }
    
    /**
     * Set the location from int coordinates.
     */
    public void setLocation(int x, int y) 
    {
        exactX = x;
        exactY = y;
        super.setLocation(x, y);
    }

    /**
     * Return the exact x-coordinate (as a double).
     */
    public double getExactX() 
    {
        return exactX;
    }

    /**
     * Return the exact y-coordinate (as a double).
     */
    public double getExactY() 
    {
        return exactY;
    }

    /**
     * Increase the speed with the given vector.
     */
    public void addForce(Vector force) 
    {
        movement.add(force);
    }
    
    /**
     * Accelerate the speed of this mover by the given factor. (Factors < 1 will
     * decelerate.)
     */
    public void accelerate(double factor)
    {
        movement.scale(factor);
        if (movement.getLength() < 0.15) {
            movement.setNeutral();
        }
    }
    
    /**
     * Return the speed of this actor.
     */
    public double getSpeed()
    {
        return movement.getLength();
    }
    
    /**
     * Stop movement of this actor.
     */
    public void stop()
    {
        movement.setNeutral();
    }
    
    /**
     * Return the current speed.
     */
    public Vector getMovement() 
    {
        return movement;
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

/**
 * A bullet that can hit asteroids.
 * 
 * @author Poul Henriksen
 */
public class Bullet extends SmoothMover
{
    /** The damage this bullet will deal */
    private static final int damage = 16;
    
    /** A bullet looses one life each act, and will disappear when life = 0 */
    private int life = 30;
    
    public Bullet()
    {
    }
    
    public Bullet(Vector speed, int rotation)
    {
        super(speed);
        setRotation(rotation);
        addForce(new Vector(rotation, 15));
        Greenfoot.playSound("EnergyGun.wav");
    }
    
    /**
     * The bullet will damage asteroids if it hits them.
     */
    public void act()
    {
        if(life <= 0) {
            getWorld().removeObject(this);
        } 
        else {
            life--;
            move();
            checkAsteroidHit();
        }
    }
    
    /**
     * Check whether we have hit an asteroid.
     */
    private void checkAsteroidHit()
    {
        Asteroid asteroid = (Asteroid) getOneIntersectingObject(Asteroid.class);
        if (asteroid != null){
            getWorld().removeObject(this);
            asteroid.hit(damage);
        }
    }
}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

/**
 * A rocket that can be controlled by the arrowkeys: up, left, right.
 * The gun is fired by hitting the 'space' key. 'z' releases a proton wave.
 * 
 * @author Poul Henriksen
 * @author Michael Kolling
 * 
 * @version 1.0
 */
public class Rocket extends SmoothMover
{
    private static final int gunReloadTime = 5;         // The minimum delay between firing the gun.
    private static final int protonReloadTime = 500;    // The minimum delay between proton wave bursts.

    private int reloadDelayCount;               // How long ago we fired the gun the last time.
    private int protonDelayCount;               // How long ago we fired the proton wave the last time.
    
    private GreenfootImage rocket = new GreenfootImage("rocket.png");    
    private GreenfootImage rocketWithThrust = new GreenfootImage("rocketWithThrust.png");

    /**
     * Initilise this rocket.
     */
    public Rocket()
    {
        reloadDelayCount = 5;
        protonDelayCount = 500;
        addForce(new Vector(13, 0.3)); // initially slowly drifting
    }

    /**
     * Do what a rocket's gotta do. (Which is: mostly flying about, and turning,
     * accelerating and shooting when the right keys are pressed.)
     */
    public void act()
    {
        move();
        checkKeys();
        checkCollision();
        reloadDelayCount++;
        protonDelayCount++;
    }
    
    /**
     * Check whether there are any key pressed and react to them.
     */
    private void checkKeys() 
    {
        ignite(Greenfoot.isKeyDown("up"));
        
        if (Greenfoot.isKeyDown("left")) 
        {
            setRotation(getRotation() - 5);
        }
        if (Greenfoot.isKeyDown("right")) 
        {
            setRotation(getRotation() + 5);
        }
        if (Greenfoot.isKeyDown("space")) 
        {
            fire();
        }
        if (Greenfoot.isKeyDown("z")) 
        {
            startProtonWave();
        }
    }
    
    /**
     * Check whether we are colliding with an asteroid.
     */
    private void checkCollision() 
    {
        Actor a = getOneIntersectingObject(Asteroid.class);
        if (a != null) 
        {
            Space space = (Space) getWorld();
            space.addObject(new Explosion(), getX(), getY());
            space.removeObject(this);
            space.gameOver();
        }
    }
    
    /**
     * Should the rocket be ignited?
     */
    private void ignite(boolean boosterOn) 
    {
        if (boosterOn) 
        {
            setImage (rocketWithThrust);
            addForce (new Vector(getRotation(), 0.3));
        }
        else 
        {
            setImage(rocket);        
        }
    }
    
    /**
     * Fire a bullet if the gun is ready.
     */
    private void fire() 
    {
        if (reloadDelayCount >= gunReloadTime) 
        {
            Bullet bullet = new Bullet (getMovement().copy(), getRotation());
            getWorld().addObject (bullet, getX(), getY());
            bullet.move ();
            reloadDelayCount = 0;
        }
    }
    
    /**
     * Release a proton wave (if it is loaded).
     */
    private void startProtonWave() 
    {
        if (protonDelayCount >= protonReloadTime) 
        {
            ProtonWave wave = new ProtonWave();
            getWorld().addObject (wave, getX(), getY());
            protonDelayCount = 0;
        }
    }

}
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

/**
 * A rock in space
 *
 * @author Poul Henriksen
 */
public class Asteroid extends SmoothMover
{
     /** Size of this asteroid */
     private int size;

     /** When the stability reaches 0 the asteroid will explode */
     private int stability;


     public Asteroid()
     {
          this(50);
     }

     public Asteroid(int size)
     {
          super(new Vector(Greenfoot.getRandomNumber(360), 2));
          setSize(size);
     }

     public Asteroid(int size, Vector speed)
     {
          super(speed);
          setSize(size);
     }

     public void act()
     {
          move();
     }

     /**
      * Set the size of this asteroid. Note that stability is directly
      * related to size. Smaller asteroids are less stable.
      */
     public void setSize(int size)
     {
          stability = size;
          this.size = size;
          GreenfootImage image = getImage();
          image.scale(size, size);
     }

     /**
      * Return the current stability of this asteroid. (If it goes down to
      * zero, it breaks up.)
      */
     public int getStability()
     {
          return stability;
     }

     /**
      * Hit this asteroid dealing the given amount of damage.
      */
     public void hit(int damage)
     {
          stability = stability - damage;
          if(stability <= 0)
               breakUp ();
     }

     /**
      * Break up this asteroid. If we are still big enough, this will create two
      * smaller asteroids. If we are small already, just disappear.
      */
     private void breakUp()
     {
          //Greenfoot.playSound("Explosion.wav");
          Space s = (Space) getWorld();
          if(size <= 16)
          {
               // Add 2 points
               s.changeScore(2);
               getWorld().removeObject(this);
          }
          else
          {
               // Add 1 point
               s.changeScore(1);
               int r = getMovement().getDirection() + Greenfoot.getRandomNumber(45);
               double l = getMovement().getLength();
               Vector speed1 = new Vector(r + 60, l * 1.2);
               Vector speed2 = new Vector(r - 60, l * 1.2);
               Asteroid a1 = new Asteroid(size/2, speed1);
               Asteroid a2 = new Asteroid(size/2, speed2);
               getWorld().addObject(a1, getX(), getY());
               getWorld().addObject(a2, getX(), getY());
               a1.move();
               a2.move();

               getWorld().removeObject(this);
          }
     }
}
import greenfoot.Greenfoot;

/**
 * A 2D vector.
 * 
 * @author Poul Henriksen
 * @author Michael Kolling
 * 
 * @version 2.0
 */
public final class Vector
{
    double dx;
    double dy;
    int direction;
    double length;
    
    /**
     * Create a new, neutral vector.
     */
    public Vector()
    {
    }

    /**
     * Create a vector with given direction and length. The direction should be in
     * the range [0..359], where 0 is EAST, and degrees increase clockwise.
     */
    public Vector(int direction, double length)
    {
        this.length = length;
        this.direction = direction;
        updateCartesian();
    }

    /**
     * Create a vector by specifying the x and y offsets from start to end points.
     */
    public Vector(double dx, double dy)
    {
        this.dx = dx;
        this.dy = dy;
        updatePolar();
    }

    /**
     * Set the direction of this vector, leaving the length intact.
     */
    public void setDirection(int direction) 
    {
        this.direction = direction;
        updateCartesian();
    }
   
    /**
     * Add another vector to this vector.
     */
    public void add(Vector other) 
    {
        dx += other.dx;
        dy += other.dy;
        updatePolar();
    }
    
    /**
     * Set the length of this vector, leaving the direction intact.
     */
    public void setLength(double length) 
    {
        this.length = length;
        updateCartesian();
    }
    
    /**
     * Scale this vector up (factor > 1) or down (factor < 1). The direction
     * remains unchanged.
     */
    public void scale(double factor) 
    {
        length = length * factor;
        updateCartesian();
    }
    
    /**
     * Set this vector to the neutral vector (length 0).
     */
    public void setNeutral() {
        dx = 0.0;
        dy = 0.0;
        length = 0.0;
        direction = 0;
    }
    
    /**
     * Revert to horizontal component of this movement vector.
     */
    public void revertHorizontal() {
        dx = -dx;
        updatePolar();
    }
    
    /**
     * Revert to vertical component of this movement vector.
     */
    public void revertVertical() {
        dy = -dy;
        updatePolar();
    }
    
    /**
     * Return the x offset of this vector (start to end point).
     */
    public double getX() {
        return dx;
    }
     
    /**
     * Return the y offset of this vector (start to end point).
     */
    public double getY() {
        return  dy;
    }
    
    /**
     * Return the direction of this vector (in degrees). 0 is EAST.
     */
    public int getDirection() {
        return direction;
    }
    
    /**
     * Return the length of this vector.
     */
    public double getLength() {
        return length;
    }

    /**
     * Update the direction and length fom the current dx, dy.
     */
    private void updatePolar() 
    {
        this.direction = (int) Math.toDegrees(Math.atan2(dy, dx));
        this.length = Math.sqrt(dx*dx+dy*dy);
    }   
    
    /**
     * Update dx and dy from the current direction and length.
     */
    private void updateCartesian() 
    {
        dx = length * Math.cos(Math.toRadians(direction));
        dy = length * Math.sin(Math.toRadians(direction));   
    }
    
    /**
     * Return a copy of this vector.
     */
    public Vector copy() 
    {
        Vector copy = new Vector();
        copy.dx = dx;
        copy.dy = dy;
        copy.direction = direction;
        copy.length = length;
        return copy;
    }    
}