import java.applet.Applet; import java.applet.*; import java.awt.*; public class bball extends Applet implements Runnable { private Color background; private Color foreground; private boolean running; public Image image; public Graphics offscreen; public Thread runner; //border sizes static final int startX=10; static final int startY=10; private int maxX; private int maxY; //sounds AudioClip beep; AudioClip hurt; //create ball objects ball ballOne = new ball(20,50,Color.red); ball ballTwo = new ball(32,78,Color.blue); public void init() { background = Color.black; foreground = Color.black; //find screen size maxX=size().width; maxY=size().height; //create offscreen image image=createImage(maxX,maxY); offscreen=image.getGraphics(); Font f=new Font("Dialog",Font.BOLD,10); offscreen.setFont(f); offscreen.drawString("Bouncing Balls 2.0",9,10); //make ball2 different direction, speed & size ballTwo.moveY=-3; ballTwo.moveX=3; ballTwo.diameter=10; //sounds beep=getAudioClip(getDocumentBase(),"beep.au"); hurt=getAudioClip(getDocumentBase(),"hurts.au"); } public void update(Graphics g) { paint(g); } public void paint(Graphics g) { offscreen.setColor(background); offscreen.fillRect(startX,startY,maxX-startX,maxY-startY); ballOne.drawBall(); ballTwo.drawBall(); g.drawImage(image,0,0,this); } public void destroy() { offscreen.dispose(); } public void start() { if (runner==null) { runner=new Thread(this); runner.start(); running=true; } } public void stop() { runner=null; } public void run() { try { while (running) { runner.sleep(40); repaint(); } } catch(InterruptedException e) { running = false; } } class ball { //instance variables int xPos; int yPos; Color ballColor; int moveX=2; int moveY=2; int diameter=20; //constructor public ball (int xPos, int yPos, Color ballColor) { this.xPos=xPos; this.yPos=yPos; this.ballColor=ballColor; } //calculate positions and draw ball to offscreen image public void drawBall() { if (xPos+moveXmaxX) { moveX*=-1; if (beep!=null) { beep.play(); } } else if (yPos+moveYmaxY) { moveY*=-1; if (hurt!=null) { hurt.play(); } } xPos+=moveX; yPos+=moveY; offscreen.setColor(ballColor); offscreen.fillOval(xPos,yPos,diameter,diameter); } } }