import java.applet.*; import java.awt.*; public class CS217 extends java.applet.Applet implements Runnable { Thread killme = null; boolean threadSuspended = false; int delay; // how much tha anim. thread sleeps Dimension dim; // the fixed size of the applet String imagename = "duke"; // image to be used for the player String imagedir = "Image"; // where image located float deltaTime = 0.2f; // time step Image imgs[]; // allow for a series of images to use int nimgs = 1; // here we use only one Image offscreenImage; // very helpful in avoiding blinking Graphics offscreenGfx; Player duke; // the one who will catch the ball public void init() { String temp; temp = getParameter("delay"); try { delay = Integer.parseInt(temp); } catch (NumberFormatException e) { delay = 100; } imgs = new Image[nimgs]; for ( int i=0; i < nimgs; i++ ) imgs[i] = getImage(getCodeBase(),imagedir + "/" + imagename + (i+1) + ".gif"); // the series of images assumed to be named duke1.gif duke2.gif ... if (size().width < 200 || size().height < 200) resize(300,400); dim = size(); // the applet area will be of fixed size duke = new Player(this); // setup the graphics buffering offscreenImage = createImage(dim.width,dim.height); offscreenGfx = offscreenImage.getGraphics(); } public void update(Graphics g){ paint(g); } void DrawBg(Graphics g){ g.setColor(Color.white); /* background is white */ g.fillRect(0,0, dim.width, dim.height); g.setColor(Color.black); /* border is black */ g.drawRect(0, 0, dim.width-1, dim.height-1); } public void paint(Graphics g) { // first, draw everything off screen DrawBg(offscreenGfx); duke.paint(offscreenGfx); // then dump the result for user's enjoyment g.drawImage(offscreenImage, 0, 0, this); } public void start() { if (killme == null) { killme = new Thread(this); killme.start(); } } public void stop() { killme = null; } public void run() { //Just to be nice, lower this thread's priority Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while (killme != null) { advance(); repaint(); try { killme.sleep(delay); } catch (InterruptedException e) { System.err.println("ERROR in run()"); break; } } killme = null; } public void advance() { duke.advance(deltaTime); // the Player class also takes care of ball } public void toggleAnim() { // Animations can be annoying! if (threadSuspended) { killme.resume(); } else { killme.suspend(); } threadSuspended = !threadSuspended; } public boolean keyDown(Event e, int key) { if (threadSuspended) return true; if ( key == ' ' ) duke.jump(); if ( key == 'j' || key == 'J') duke.moveinX(-5); if ( key == 'k' || key == 'K' ) duke.moveinX(5); return true; } public boolean mouseDown(Event evt, int x, int y) { toggleAnim(); return true; } }