GAMES LESSON FOUR: Using a Vector To Manage Threads
We use a vector to keep track of many instances of the DROPPING thread class
in the POOL applet. We must add elements to the vector, remove them, and we
must know how to access them. You can find examples of each of these in the
following code.
POOL.java
import java.awt.*;
import java.applet.*;
import java.util.*;
public class POOL extends Applet{
Color colors[] = { Color.red, Color.green, Color.magenta,
Color.yellow, Color.cyan, Color.blue, Color.white};
Vector v;
Dimension d;
Image offI;
Random r;
public void init(){
d = getSize();
offI=createImage(d.width,d.height);
r = new Random();
v = new Vector(10);
for(int i = 0; i<8; i++){
int c=Math.abs(r.nextInt()%colors.length);
int x = Math.abs(r.nextInt()%380)+10;
int s = Math.abs(r.nextInt()%20)+5;
int sp = Math.abs(r.nextInt()%300)+150;
DROPPING drop = new DROPPING(this,x,colors[c],s,sp);
drop.start();
v.add(drop);
}
new Thread(){
public void run(){
while(true){
repaint();
try{
Thread.sleep(100);
}catch(InterruptedException e){};
}
}
}.start();
}
public void newBall(){
int c=Math.abs(r.nextInt()%colors.length);
int x = Math.abs(r.nextInt()%400)+20;
int s = Math.abs(r.nextInt()%20)+5;
int sp =Math.abs(r.nextInt()%300)+100;
DROPPING drop = new DROPPING(this,x,colors[c],s,sp);
drop.start();
v.add(drop);
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
Graphics offG = offI.getGraphics();
offG.setColor(Color.black);
offG.fillRect(0,0,d.width,d.height);
for(int i=0; i
DROPPING.java
import java.awt.*;
public class DROPPING extends Thread{
int y, x;
POOL app;
Color c;
int size;
int speed;
DROPPING(POOL p, int xval, Color cval, int s, int sp){
app = p;
x = xval;
c = cval;
size = s;
speed = sp;
}
public void run(){
y=0;
while(y<200){
y+=3;
try{
Thread.sleep(speed);
}catch(InterruptedException ie){}
}
app.newBall();
app.v.remove(this);
}
public void draw(Graphics g){
g.setColor(c);
g.fillOval(x,y,size,size);
}
}
ASSIGNMENT: