Advertisement
Guest User

MyCode

a guest
May 30th, 2015
301
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.52 KB | None | 0 0
  1. package io.stevenpg;
  2.  
  3. // This class primarily uses the weaker java.awt library for
  4. //      window operations.
  5. import java.awt.*;
  6. import java.awt.event.*;
  7. import java.io.File;
  8. import java.io.IOException;
  9. import java.util.Random;
  10. import java.util.Vector;
  11.  
  12. @SuppressWarnings("serial")
  13. /**
  14.  *
  15.  * @author Steven Gantz
  16.  * @Github: https://github.com/StevenPG/Java-Aquarium
  17.  * @Date: 5/30/2015
  18.  *
  19.  */
  20. public class Aquarium extends Frame implements Runnable{
  21.    
  22.     // Handle visuals within awt.Frame
  23.     MediaTracker tracker;
  24.    
  25.     // Image attributes
  26.     Image aquariumImage, memoryImage;
  27.     Image[] fishImages = new Image[2];
  28.    
  29.     // Main thread implementing Runnable
  30.     Thread thread;
  31.    
  32.     // Handle fish objects
  33.     int numberOfFish = 6;
  34.     int sleepTime = 110;
  35.    
  36.     // Continue fish swimming
  37.     boolean runOK = true;
  38.    
  39.     // Vectors are thread safe, unlike ArrayLists, and must be used
  40.     //      for this application.
  41.     Vector<Fish> fishes = new Vector<Fish>();
  42.    
  43.     /*
  44.      * Use this object to perform double buffering.
  45.      * To avoid drawing a fish, updating display, and repeat
  46.      * which causes flickering, use double buffering to draw
  47.      * completed scene on screen all at once.
  48.      */
  49.     Graphics memoryGraphics;
  50.    
  51.     Aquarium(){
  52.         setTitle("The Aquarium");
  53.        
  54.         // Initialize Graphical Elements
  55.         tracker = new MediaTracker(this);
  56.        
  57.         // Handle fish graphics
  58.         fishImages[0] = Toolkit.getDefaultToolkit().getImage
  59.                 ("fish1.gif");
  60.         tracker.addImage(fishImages[0], 0);
  61.         fishImages[1] = Toolkit.getDefaultToolkit().getImage
  62.                 ("fish2.gif");
  63.         tracker.addImage(fishImages[1], 0);
  64.        
  65.         // Handle aquarium background graphics
  66.         aquariumImage = Toolkit.getDefaultToolkit().getImage
  67.                 ("bubbles.gif");
  68.         tracker.addImage(aquariumImage, 0);
  69.        
  70.         // start loading images tracked buy tracker w/ identifier
  71.         try{
  72.             tracker.waitForID(0);
  73.            
  74.             // See if tracker errored out
  75.             if (tracker.isErrorAny()){
  76.                 throw new Exception();
  77.             }
  78.            
  79.         } catch(Exception ex){
  80.             System.out.println("Waiting for ID failed...");
  81.             System.out.println(ex.getMessage());
  82.             ex.printStackTrace();
  83.         }
  84.        
  85.         // Assign window attributes
  86.         setSize(aquariumImage.getWidth(this),
  87.             aquariumImage.getHeight(this));
  88.         setResizable(false);
  89.         setVisible(true);
  90.        
  91.         // Create double-buffer image
  92.         memoryImage = createImage(getSize().width, getSize().height);
  93.         memoryGraphics = memoryImage.getGraphics();
  94.        
  95.         // Create and start the thread
  96.         thread = new Thread(this);
  97.         thread.start();
  98.        
  99.         // Handle when the X button is clicked
  100.         this.addWindowListener(new WindowAdapter(){
  101.             public void windowClosing(
  102.                 WindowEvent windowEvent){
  103.                     // Clean up application and signal end threads
  104.                     runOK = false;
  105.                     System.exit(0);
  106.                 }
  107.             }
  108.         );
  109.     }
  110.     // Static main method, the main driver of the program
  111.     public static void main(String[] args){
  112.         new Aquarium();
  113.     }
  114.     // Thread execution that actually creates fish
  115.     public void run(){
  116.         Rectangle edges = new Rectangle(
  117.                 0 + getInsets().left, // Get left edge
  118.                 0 + getInsets().top,  // Get top edge
  119.                 getSize().width - (getInsets().left + getInsets().right), // Get right edge
  120.                 getSize().height - (getInsets().top + getInsets().bottom) // Get left edge
  121.         );
  122.        
  123.         for (int loopIndex = 0; loopIndex < numberOfFish; loopIndex++){
  124.             fishes.add(new Fish(fishImages[0],
  125.                 fishImages[1], edges,this));
  126.             try{
  127.                 // Each fish uses this time to generate its random position and velocity
  128.                 Thread.sleep(20);
  129.             }catch(Exception exp){
  130.                 System.out.println("Attempted to sleep for the fishes...");
  131.                 System.out.println(exp.getMessage());
  132.                 exp.printStackTrace();
  133.             }
  134.         }
  135.        
  136.         // Actually run the tank
  137.         Fish fish;
  138.        
  139.         while (runOK) {
  140.             for (int loopIndex = 0; loopIndex < numberOfFish; loopIndex++){
  141.                 // Get fish, tell it to swim
  142.                 fish = (Fish)fishes.elementAt(loopIndex);
  143.                 fish.swim();
  144.             }
  145.         }
  146.        
  147.         // Wait between each execution
  148.         try {
  149.             Thread.sleep(sleepTime);
  150.         }catch(Exception exp){
  151.             System.out.println("Tried to wait between method calls...");
  152.             System.out.println(exp.getMessage());
  153.             exp.printStackTrace();
  154.         }
  155.        
  156.         // Redraw the scene
  157.         repaint();
  158.        
  159.     }
  160.    
  161.     // Update method to handle double-buffering
  162.     public void update(Graphics g){
  163.         // Draw tank and fish
  164.         memoryGraphics.drawImage(aquariumImage, 0, 0, this);
  165.         for(int loopIndex = 0; loopIndex < numberOfFish; loopIndex++){
  166.             ((Fish)fishes.elementAt(loopIndex)).drawFishImage
  167.                 (memoryGraphics);
  168.         }
  169.        
  170.         g.drawImage(memoryImage, 0, 0, this);
  171.     }
  172.    
  173.     // Internal Fish class
  174.     class Fish{
  175.         // Fish attributes
  176.         Component tank;
  177.         Image image1;
  178.         Image image2;
  179.         Point location;
  180.         Point velocity;
  181.         Rectangle edges;
  182.         Random random;
  183.        
  184.         public Fish(Image image1, Image image2, Rectangle edges, Component tank){
  185.             random = new Random(System.currentTimeMillis());
  186.             this.tank = tank;
  187.             this.image1 = image1;
  188.             this.image2 = image2;
  189.             this.edges = edges;
  190.             this.location = new Point(
  191.                     100 + (Math.abs(random.nextInt()) % 300),
  192.                     100 + (Math.abs(100 + random.nextInt()) % 100)
  193.                     );
  194.             this.velocity = new Point(random.nextInt() % 8, random.nextInt() % 8);
  195.         }
  196.        
  197.         // Handle the fish's moving
  198.         public void swim(){
  199.             if(random.nextInt() % 7 <= 1){
  200.                 velocity.x += random.nextInt() % 4;
  201.                
  202.                 // Keep the velocity within -8 and 8
  203.                 velocity.x = Math.min(velocity.x, 8);
  204.                 velocity.x = Math.max(velocity.x, -8);
  205.                
  206.                 velocity.y += random.nextInt() % 4;
  207.                
  208.                 velocity.y = Math.min(velocity.y, 8);
  209.                 velocity.y = Math.max(velocity.y, -8);
  210.             }
  211.            
  212.             // Assign new location
  213.             location.x += velocity.x;
  214.             location.y += velocity.y;
  215.            
  216.             // Determine if the fish's position has put it beyond the
  217.             //  edge of the tank. This creates the "bounce-off" effect.
  218.             if(location.x < edges.x){
  219.                 location.x = edges.x;
  220.                 velocity.x = -velocity.x;
  221.             }
  222.             if((location.x + image1.getWidth(tank)) > (edges.x + edges.width)){
  223.                 location.x = edges.x + edges.width - image1.getWidth(tank);
  224.                 velocity.x = -velocity.x;
  225.             }
  226.             if(location.y < edges.y){
  227.                 location.y = edges.y;
  228.                 velocity.y = -velocity.y;
  229.             }
  230.             if((location.y + image1.getHeight(tank)) > (edges.y + edges.height)){
  231.                 location.y = edges.y + edges.height - image1.getHeight(tank);
  232.                 velocity.y = -velocity.y;
  233.             }
  234.         }
  235.    
  236.         // Draw the fish
  237.         public void drawFishImage(Graphics g){
  238.             if(velocity.x < 0){
  239.                 g.drawImage(image1, location.x, location.y, tank);
  240.             }
  241.             else {
  242.                 g.drawImage(image2, location.x, location.y, tank);
  243.             }
  244.         }
  245.     }
  246.    
  247. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement