/** * File: SpaceshipGenerator.java * Author: Brian Borowski * Date created: August 1, 2011 * Date last modified: January 1, 2013 */ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class SpaceshipGenerator implements ActionListener { private final JPanel parent; private final Spaceship[] spaceships; private long lastLaunchTime; private int sleepMilliseconds; private Timer timer; public SpaceshipGenerator(final JPanel parent, final Spaceship[] spaceships) { this.parent = parent; this.spaceships = spaceships; sleepMilliseconds = 0; timer = new Timer(10, this); } public void start() { for (int i = spaceships.length - 1; i >= 0; --i) { spaceships[i] = null; } resume(); } public void stop() { pause(); for (int i = spaceships.length - 1; i >= 0; --i) { spaceships[i] = null; } } public void update(final float elapsedSeconds) { for (int i = spaceships.length - 1; i >= 0; --i) { if (spaceships[i] != null) { spaceships[i].move(elapsedSeconds); } } } public void resume() { timer.start(); } public void pause() { timer.stop(); } public void actionPerformed(final ActionEvent ae) { final long now = System.currentTimeMillis(); if (now - lastLaunchTime >= sleepMilliseconds) { lastLaunchTime = now; sleepMilliseconds = GamePanel.RANDOM_GENERATOR.nextInt(2000); final int numToCreate = GamePanel.RANDOM_GENERATOR.nextInt(spaceships.length); int numCreated = 0; for (int i = spaceships.length - 1; i >= 0; --i) { if (spaceships[i] == null) { final int speed = 100 * (GamePanel.RANDOM_GENERATOR.nextInt(2) + 1), pointsEarned = speed / 10, pointsLost = 10 * (1 - (speed/100 - 1) + 1); spaceships[i] = new Spaceship(parent, 50 * (i + 1), GamePanel.RANDOM_GENERATOR.nextInt(2), speed, pointsEarned, pointsLost ); ++numCreated; } if (numCreated == numToCreate) { break; } } } } }