Tuesday, March 25, 2014

Colorful Bouncing Ball using Java applet





import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="bb" width=500 height=400></applet>*/

public class bb extends Applet implements Runnable {
  int x,y,dx,dy,diam,sizex,sizey;

  public void init() {

    sizex=Integer.parseInt(getParameter("WIDTH"));
    sizey=Integer.parseInt(getParameter("HEIGHT"));

    x=(int)(Math.random()*1000)%sizex;
    y=(int)(Math.random()*1000)%sizey;

    dx=dy=5; diam=20;

setBackground(Color.black);
   (new Thread(bb.this)).start();

  }

  public void run() {
    while (true) {
      try {
        Thread.sleep(50);
      }
      catch (InterruptedException e) {};

      x+=dx; y+=dy;
      if ((x<=0)||(x+dx+diam>=sizex))
      dx=-dx;
      if ((y<=0)||(y+dy+diam>=sizey))
      dy=-dy;

      repaint();
    }
  }

  public void paint(Graphics g) {

    g.setColor(new Color((int)(Math.random()*1000)%254,(int)(Math.random()*1000)%254,(int)(Math.random()*1000)%254));
g.fillOval(x,y,diam,diam);

  }
}

No comments: