import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; import javax.swing.Timer; public class BouncingLinesWithSound implements ActionListener { private Random rand = new Random(); private Timer myTimer; private Picture myPic; //TODO: Changed form Graphics private Graphics2D canvas; //TODO: Requires SoundPlayer.java to be in same project src folder as this file private SoundPlayer boinkSound; private static final int DRAW_WIDTH = 600; private static final int DRAW_HEIGHT = 600; private int x1, y1, x2, y2; private int x3, y3, x4, y4; private int speedX1, speedX2, speedY1, speedY2; private int speedX3, speedX4, speedY3, speedY4; ////////////////////////////////////////////////////////////////////// // BouncingLine Constructor. This constructor: // 1) Creates an empty Picture Frame // 2) Sets the initial location, and speed of each end point of a line. // 3) Start the timer. ///////////////////////////////////////////////////////////////////// public BouncingLinesWithSound() { myPic = new Picture(DRAW_WIDTH, DRAW_HEIGHT); //TODO //If you want a Graphics2D rather than a graphics, just cast // the value returned by myPic.getOffScreenGraphics() canvas = (Graphics2D)myPic.getOffScreenGraphics(); canvas.setColor(Color.WHITE); canvas.fillRect(0, 0, DRAW_WIDTH, DRAW_HEIGHT); myPic.setTitle("Bouncing Line"); x1 = rand.nextInt(DRAW_WIDTH); y1 = rand.nextInt(DRAW_HEIGHT); x2 = rand.nextInt(DRAW_WIDTH); y2 = rand.nextInt(DRAW_HEIGHT); x3 = rand.nextInt(DRAW_WIDTH); y3 = rand.nextInt(DRAW_HEIGHT); x4 = rand.nextInt(DRAW_WIDTH); y4 = rand.nextInt(DRAW_HEIGHT); speedX1 = rand.nextInt(25)-12; speedY1 = rand.nextInt(25)-12; speedX2 = rand.nextInt(25)-12; speedY2 = rand.nextInt(25)-12; speedX3 = rand.nextInt(25)-12; speedY3 = rand.nextInt(25)-12; speedX4 = rand.nextInt(25)-12; speedY4 = rand.nextInt(25)-12; //////////////////////////////////////////// try { boinkSound = new SoundPlayer(); } catch (Exception e) { System.out.println("BouncingLinesWithSound():: "+e.getMessage()); System.exit(0); } myTimer = new Timer(30, this); // miliseconds myTimer.start(); } /////////////////////////////////////////////////////////////////////// // Called each time the timer fires. // 1) Erase the current line // 2) Move the two end points of the line. // 3) Check to see if either end point moved outside the frame. If so, // give that end point a random speed in the direction away from // the edge it moved off. // 4) Draw the line in its new location. //////////////////////////////////////////////////////////////////////// public void actionPerformed(ActionEvent arg0) { //Erase Line in its current location canvas.setColor(Color.WHITE); canvas.drawLine(x1, y1, x2, y2); canvas.drawLine(x3, y3, x4, y4); x1 += speedX1*2; y1 += speedY1*2; x2 += speedX2; y2 += speedY2; x3 += speedX3*2; y3 += speedY3*2; x4 += speedX4; y4 += speedY4; boolean hit = false; if (x1 < 0) { speedX1 = rand.nextInt(12)+1; hit = true; } else if (x1 > DRAW_WIDTH) { speedX1 = -(rand.nextInt(12)+1); hit = true; } if (y1 < 0) { speedY1 = rand.nextInt(12)+1; hit = true; } else if (y1 > DRAW_HEIGHT) { speedY1 = -(rand.nextInt(12)+1); hit = true; } if (x2 < 0) { speedX2 = rand.nextInt(12)+1; hit = true; } else if (x2 > DRAW_WIDTH) { speedX2 = -(rand.nextInt(12)+1); hit = true; } if (y2 < 0) { speedY2 = rand.nextInt(12)+1; hit = true; } else if (y2 > DRAW_HEIGHT) { speedY2 = -(rand.nextInt(12)+1); hit = true; } if (x3 < 0) { speedX3 = rand.nextInt(12)+1; hit = true; } else if (x3 > DRAW_WIDTH) { speedX3 = -(rand.nextInt(12)+1); hit = true; } if (y3 < 0) { speedY3 = rand.nextInt(12)+1; hit = true; } else if (y3 > DRAW_WIDTH) { speedY3 = -(rand.nextInt(12)+1); hit = true; } if (x4 < 0) { speedX4 = rand.nextInt(12)+1; hit = true; } else if (x4 > DRAW_WIDTH) { speedX4 = -(rand.nextInt(12)+1); hit = true; } if (y4 < 0) { speedY4 = rand.nextInt(12)+1; hit = true; } else if (y4 > DRAW_WIDTH) { speedY4 = -(rand.nextInt(12)+1); hit = true; } if (hit) boinkSound.play(); //Draw Line in new location canvas.setColor(Color.RED); canvas.drawLine(x1, y1, x2, y2); canvas.setColor(Color.BLUE); canvas.drawLine(x3, y3, x4, y4); myPic.repaint(); } ///////////////////////////////////////////////////////////////////// // Create and run BouncingLinesWithSound ///////////////////////////////////////////////////////////////////// public static void main(String[] args) { new BouncingLinesWithSound(); } }
I'm working on this small program that has to have two lines bouncing around and colliding with the edges of the window and with themselves.
I am really stumped on how to get the two lines to collide with each other and was hoping someone could possibly give me a push in the right direction.
Other Classes:
Picture.java
import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.awt.Color; import java.awt.Component; import java.awt.Insets; import java.awt.MediaTracker; import java.awt.Toolkit; import java.io.File; import javax.imageio.ImageIO; import javax.swing.JFileChooser; import javax.swing.JFrame; public class Picture extends JFrame { public static final String VERSION = "Picture Version 2013.2.14"; private int imageWidth, imageHeight; private BufferedImage userImage; private int insideLeft, insideTop; //Constructor to create an empty picture of a specified inside size public Picture(int insideWidth, int insideHeight) { this.setTitle(VERSION); imageWidth = insideWidth; imageHeight = insideHeight; userImage = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB); addSpaceToFrameForBoarder(); } //Constructor to ask user for image file and create a Picture with that image public Picture() { String userFilePath = pickFile(); userImage = loadImage(userFilePath, this); if (userFilePath == null) { imageWidth = 250; imageHeight = 250; } else { this.setTitle(userFilePath); imageWidth = userImage.getWidth(); imageHeight = userImage.getHeight(); } addSpaceToFrameForBoarder(); } private void addSpaceToFrameForBoarder() { this.setSize(imageWidth, imageHeight); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); Insets inset = this.getInsets(); insideLeft = inset.left; insideTop = inset.top; int frameWidth = imageWidth + inset.left + inset.right; int frameHeight = imageHeight + inset.top + inset.bottom; this.setSize(frameWidth, frameHeight); System.out.println("frame size="+frameWidth+", " +frameHeight); } private static String pickFile() { String dir = System.getProperty("user.dir"); JFileChooser fileChooser = new JFileChooser(dir); int returnVal = fileChooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); String imagePath = file.getPath(); System.out.println("You selected file: ["+imagePath+"]"); return imagePath; } return null; } private static BufferedImage loadImage(String imagePath, Component window) { if (imagePath == null) return null; // Create a MediaTracker instance, to montior loading of images MediaTracker tracker = new MediaTracker(window); // load each image and register it, // using the MediaTracker.addImage (Image, int) method. // It takes as its first parameter an image, // and the idcode of the image as its second parameter. // The idcode can be used to inquire about the status of // a particular image, rather than a group of images. // Load the image Toolkit tk = Toolkit.getDefaultToolkit(); Image loadedImage = tk.getImage(imagePath); // Register it with media tracker tracker.addImage(loadedImage, 1); try { tracker.waitForAll(); } catch (Exception e){} int width = loadedImage.getWidth(null); int height = loadedImage.getHeight(null); BufferedImage imageBuffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = imageBuffer.getGraphics(); g.drawImage(loadedImage, 0, 0, null); return imageBuffer; } public Graphics getOffScreenGraphics() { return userImage.getGraphics(); } public int getImageWidth() { return userImage.getWidth(); } public int getImageHeight() { return userImage.getHeight(); } public int getRed(int x, int y) { int rgb = userImage.getRGB(x, y); int red = (rgb & 0x00FF0000) >> 16; return red; } public int getGreen(int x, int y) { int rgb = userImage.getRGB(x, y); int green = (rgb & 0x0000FF00) >> 8; return green; } public int getBlue(int x, int y) { int rgb = userImage.getRGB(x, y); int blue = rgb & 0x000000FF; return blue; } public void setRGB(int x, int y, int r, int g, int b) { if (x<0) return; if (y<0) return; if (x>imageWidth) return; if (y>imageHeight) return; if (r<0 || g<0 || b<0) return; if (r>255 || g>255 || b>255) return; int rgb = (r<<16) | (g<<8) | b; userImage.setRGB(x, y, rgb); } public void setColor(int x, int y, Color c) { setRGB(x, y, c.getRed(), c.getGreen(), c.getBlue()); } public void saveImage() { JFileChooser fileChooser = new JFileChooser(); int returnValue = fileChooser.showSaveDialog(null); if (returnValue != JFileChooser.APPROVE_OPTION) return; File inputFile = fileChooser.getSelectedFile(); String path = inputFile.getAbsolutePath(); if ((path.endsWith(".png") == false) && (path.endsWith(".PNG") == false)) { path = path+".png"; } File myFile = new File(path); try { ImageIO.write(userImage, "png", myFile); } catch (Exception e){ e.printStackTrace();} } public void paint(Graphics canvas) { canvas.drawImage(userImage, insideLeft, insideTop, null); }
Soundplayer.java
import java.applet.Applet; import java.applet.AudioClip; import java.io.File; import java.lang.IllegalArgumentException; import java.net.URL; import javax.swing.JFileChooser; public class SoundPlayer { private AudioClip soundEffect; // Sound player public SoundPlayer() throws Exception { String wavfile = pickFile(); loadClip(wavfile); } public SoundPlayer(String wavfile) throws Exception { if (wavfile == null) { throw new IllegalArgumentException( "SoundPlayer(): file is null"); } // Note: if wavfile is null, then this will through a NullPointerException if (!wavfile.endsWith(".wav") && !wavfile.endsWith(".WAV")) { throw new IllegalArgumentException( "SoundPlayer(): File name must end with .wav"); } loadClip(wavfile); } private void loadClip(String wavfile) throws Exception { try { File file = new File(wavfile); soundEffect = Applet.newAudioClip(file.toURI().toURL()); if (soundEffect == null) throw new Exception(); System.out.println("SoundPlayer(" + wavfile + ")"); } catch (Exception e) { throw new IllegalArgumentException("SoundPlayer(): Cannot open file:" + wavfile); } } //========================================================================= // pickFile() //========================================================================= private static String pickFile() { String dir = System.getProperty("user.dir"); JFileChooser fileChooser = new JFileChooser(dir); int returnVal = fileChooser.showOpenDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); String imagePath = file.getPath(); System.out.println("You selected file: ["+imagePath+"]"); return imagePath; } return null; } // Plays in a new thread public void play() { soundEffect.play(); // Play only once } public void stop() { soundEffect.stop(); } }