GAMES LESSON ONE: TimerTask

In order to produce animation of any kind you must have some sort of delay and redraw mechanism in place. The TimerTask and Timer classes provide this sort of functionality. These classes are part of the java.util package and so you will need to import this package as shown in the code below.

// Timer Task Example: import java.awt.*; import java.applet.*; import java.util.*; public class TT extends Applet { Image offI; Dimension d; int x=10; public void init(){ d = getSize(); offI = createImage(d.width, d.height); TimerTask task = new TimerTask(){ public void run(){ boolean move_rt = true; while(true){ if(move_rt && x>390){ move_rt = false; } if(!move_rt && x<5){ move_rt = true; } if(move_rt) mvX(3); else mvX(-3); try{ Thread.sleep(100); }catch(InterruptedException e){}; } } }; Timer t = new Timer(); t.schedule(task,100); } public void mvX(int i){ x+=i; 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); offG.setColor(Color.blue); offG.fillOval(x,40,40,40); g.drawImage(offI,0,0,this); } }


ASSIGNMENT: