S O U R C E C O D E
/ 1999 / 11
/ java
/ 4.lst
// The Ballz animation applet
import java.awt.*;
public class Ballz extends AniApplet
{
final int numballs=8; // number of balls
final int grid=25; // grid spacing
Ball[] balls;
// paint a grid
public void paintGrid(Graphics g)
{
int i;
// draw grid
for (i=grid;i<getSize().height;i+=grid)
g.drawLine(0,i,getSize().width,i);
for (i=grid;i<getSize().width;i+=grid)
g.drawLine(i,0,i,getSize().height);
}
public void init()
{
Graphics g=getVirtualGraphics();
int i;
paintGrid(g); // grid is constant on background
// initialize the ball array
balls = new Ball[numballs];
for (i=0;i<numballs;i++) balls[i]=new Ball();
for (i=0;i<numballs;i++)
{
// set random start conditions
balls[i].x=Math.random()*getSize().width;
balls[i].y=Math.random()*getSize().height;
balls[i].maxheight=(int)(getSize().height-
Math.random()*getSize().height/2);
balls[i].maxwidth=getSize().width;
balls[i].color=new Color((int)(Math.random()*0xFFFFFF));
balls[i].speed=Math.random()*.8 + .2;
if (Math.random()>.5) balls[i].dir=-1;
}
}
// This is the animation routine
public void animate()
{
int i;
// move balls
for (i=0;i<numballs;i++) balls[i].step();
// repaint
repaint();
}
public void paint(Graphics g)
{
super.paint(g); // let parent draw background
int i;
Color oldcolor = g.getColor();
// draw each ball
for (i=0;i<numballs;i++)
{
int x1,y1;
x1=(int) balls[i].x;
y1=getSize().height-(int) balls[i].y;
g.setColor(balls[i].color);
g.fillOval(x1-10,y1-10,20,20);
}
g.setColor(oldcolor);
}
}
|
home
|
current issue
|
archives
|
source code
|
demo express
|
events
|
search
|
editorial calendar
|
advertising
|
customer service
|
author guidelines
|
jobs
|
about
Entire contents copyright 1996-2000 CMP Media Inc.
Read our privacy policy.