GAMES LESSON NINE: Many Sprites

Keeping track of many sprites simultaneously can be accomplished in a few different ways. Probably the simplest is to use arrays to keep track of the data. For loops are used in the run and paint methods to deal with six sprites in the following applet. Other than this and the conversion of some int variables into arrays of int (and the addition of an array to deal with color), this applet is exactly the same as the one from the last lesson!

import java.awt.*; import java.applet.*; public class MANY extends Applet implements Runnable{ Dimension d; Image offI; Thread tt; int xDIR[]={4,3,5,8,6,7}; int yDIR[]={3,5,3,2,8,4}; int xLOC[]={20,20,20,20,20,20}; int yLOC[]={5,5,5,5,5,5}; Color colors[] = { Color.blue, Color.red, Color.cyan, Color.green, Color.magenta, Color.black }; public void init(){ d = getSize(); offI=createImage(d.width,d.height); tt = new Thread(this); tt.start(); } public void run(){ while(true){ for(int i=0; i<xDIR.length; i++){ if(xDIR[i]>0 && xLOC[i]>d.width-15 || xDIR[i]<0 && xLOC[i]<0 ) xDIR[i]*=-1; if(yDIR[i]>0 && yLOC[i]>d.height-15 || yDIR[i]<0 && yLOC[i]<0) yDIR[i]*=-1; xLOC[i]+=xDIR[i]; yLOC[i]+=yDIR[i]; } try{ Thread.sleep(50); }catch(InterruptedException ie){ } repaint(); } } public void update(Graphics g){ paint(g); } public void paint(Graphics g){ Graphics offG = offI.getGraphics(); offG.setColor(Color.yellow); offG.fillRect(0,0,d.width,d.height); for(int i = 0; i<colors.length; i++){ offG.setColor(colors[i]); offG.fillOval(xLOC[i],yLOC[i],15,15); } g.drawImage(offI,0,0,this); offG.dispose(); } }


ASSIGNMENT: