Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package io.stevenpg;
- // This class primarily uses the weaker java.awt library for
- // window operations.
- import java.awt.*;
- import java.awt.event.*;
- import java.io.File;
- import java.io.IOException;
- import java.util.Random;
- import java.util.Vector;
- @SuppressWarnings("serial")
- /**
- *
- * @author Steven Gantz
- * @Github: https://github.com/StevenPG/Java-Aquarium
- * @Date: 5/30/2015
- *
- */
- public class Aquarium extends Frame implements Runnable{
- // Handle visuals within awt.Frame
- MediaTracker tracker;
- // Image attributes
- Image aquariumImage, memoryImage;
- Image[] fishImages = new Image[2];
- // Main thread implementing Runnable
- Thread thread;
- // Handle fish objects
- int numberOfFish = 6;
- int sleepTime = 110;
- // Continue fish swimming
- boolean runOK = true;
- // Vectors are thread safe, unlike ArrayLists, and must be used
- // for this application.
- Vector<Fish> fishes = new Vector<Fish>();
- /*
- * Use this object to perform double buffering.
- * To avoid drawing a fish, updating display, and repeat
- * which causes flickering, use double buffering to draw
- * completed scene on screen all at once.
- */
- Graphics memoryGraphics;
- Aquarium(){
- setTitle("The Aquarium");
- // Initialize Graphical Elements
- tracker = new MediaTracker(this);
- // Handle fish graphics
- fishImages[0] = Toolkit.getDefaultToolkit().getImage
- ("fish1.gif");
- tracker.addImage(fishImages[0], 0);
- fishImages[1] = Toolkit.getDefaultToolkit().getImage
- ("fish2.gif");
- tracker.addImage(fishImages[1], 0);
- // Handle aquarium background graphics
- aquariumImage = Toolkit.getDefaultToolkit().getImage
- ("bubbles.gif");
- tracker.addImage(aquariumImage, 0);
- // start loading images tracked buy tracker w/ identifier
- try{
- tracker.waitForID(0);
- // See if tracker errored out
- if (tracker.isErrorAny()){
- throw new Exception();
- }
- } catch(Exception ex){
- System.out.println("Waiting for ID failed...");
- System.out.println(ex.getMessage());
- ex.printStackTrace();
- }
- // Assign window attributes
- setSize(aquariumImage.getWidth(this),
- aquariumImage.getHeight(this));
- setResizable(false);
- setVisible(true);
- // Create double-buffer image
- memoryImage = createImage(getSize().width, getSize().height);
- memoryGraphics = memoryImage.getGraphics();
- // Create and start the thread
- thread = new Thread(this);
- thread.start();
- // Handle when the X button is clicked
- this.addWindowListener(new WindowAdapter(){
- public void windowClosing(
- WindowEvent windowEvent){
- // Clean up application and signal end threads
- runOK = false;
- System.exit(0);
- }
- }
- );
- }
- // Static main method, the main driver of the program
- public static void main(String[] args){
- new Aquarium();
- }
- // Thread execution that actually creates fish
- public void run(){
- Rectangle edges = new Rectangle(
- 0 + getInsets().left, // Get left edge
- 0 + getInsets().top, // Get top edge
- getSize().width - (getInsets().left + getInsets().right), // Get right edge
- getSize().height - (getInsets().top + getInsets().bottom) // Get left edge
- );
- for (int loopIndex = 0; loopIndex < numberOfFish; loopIndex++){
- fishes.add(new Fish(fishImages[0],
- fishImages[1], edges,this));
- try{
- // Each fish uses this time to generate its random position and velocity
- Thread.sleep(20);
- }catch(Exception exp){
- System.out.println("Attempted to sleep for the fishes...");
- System.out.println(exp.getMessage());
- exp.printStackTrace();
- }
- }
- // Actually run the tank
- Fish fish;
- while (runOK) {
- for (int loopIndex = 0; loopIndex < numberOfFish; loopIndex++){
- // Get fish, tell it to swim
- fish = (Fish)fishes.elementAt(loopIndex);
- fish.swim();
- }
- }
- // Wait between each execution
- try {
- Thread.sleep(sleepTime);
- }catch(Exception exp){
- System.out.println("Tried to wait between method calls...");
- System.out.println(exp.getMessage());
- exp.printStackTrace();
- }
- // Redraw the scene
- repaint();
- }
- // Update method to handle double-buffering
- public void update(Graphics g){
- // Draw tank and fish
- memoryGraphics.drawImage(aquariumImage, 0, 0, this);
- for(int loopIndex = 0; loopIndex < numberOfFish; loopIndex++){
- ((Fish)fishes.elementAt(loopIndex)).drawFishImage
- (memoryGraphics);
- }
- g.drawImage(memoryImage, 0, 0, this);
- }
- // Internal Fish class
- class Fish{
- // Fish attributes
- Component tank;
- Image image1;
- Image image2;
- Point location;
- Point velocity;
- Rectangle edges;
- Random random;
- public Fish(Image image1, Image image2, Rectangle edges, Component tank){
- random = new Random(System.currentTimeMillis());
- this.tank = tank;
- this.image1 = image1;
- this.image2 = image2;
- this.edges = edges;
- this.location = new Point(
- 100 + (Math.abs(random.nextInt()) % 300),
- 100 + (Math.abs(100 + random.nextInt()) % 100)
- );
- this.velocity = new Point(random.nextInt() % 8, random.nextInt() % 8);
- }
- // Handle the fish's moving
- public void swim(){
- if(random.nextInt() % 7 <= 1){
- velocity.x += random.nextInt() % 4;
- // Keep the velocity within -8 and 8
- velocity.x = Math.min(velocity.x, 8);
- velocity.x = Math.max(velocity.x, -8);
- velocity.y += random.nextInt() % 4;
- velocity.y = Math.min(velocity.y, 8);
- velocity.y = Math.max(velocity.y, -8);
- }
- // Assign new location
- location.x += velocity.x;
- location.y += velocity.y;
- // Determine if the fish's position has put it beyond the
- // edge of the tank. This creates the "bounce-off" effect.
- if(location.x < edges.x){
- location.x = edges.x;
- velocity.x = -velocity.x;
- }
- if((location.x + image1.getWidth(tank)) > (edges.x + edges.width)){
- location.x = edges.x + edges.width - image1.getWidth(tank);
- velocity.x = -velocity.x;
- }
- if(location.y < edges.y){
- location.y = edges.y;
- velocity.y = -velocity.y;
- }
- if((location.y + image1.getHeight(tank)) > (edges.y + edges.height)){
- location.y = edges.y + edges.height - image1.getHeight(tank);
- velocity.y = -velocity.y;
- }
- }
- // Draw the fish
- public void drawFishImage(Graphics g){
- if(velocity.x < 0){
- g.drawImage(image1, location.x, location.y, tank);
- }
- else {
- g.drawImage(image2, location.x, location.y, tank);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement