//Kite2.java //Add Thread and motion //Andy Harris, 06/00 import java.awt.*; import java.applet.*; import java.awt.event.*; public class Kite2 extends Applet implements Runnable { public static final int NORTH = 0; public static final int NORTHEAST = 1; public static final int EAST = 2; public static final int SOUTHEAST = 3; public static final int SOUTH = 4; public static final int SOUTHWEST = 5; public static final int WEST = 6; public static final int NORTHWEST = 7; Image kite[] = new Image[8]; int direction = NORTH; int dx = 0; int dy = 0; int x = 0; int y = 0; EventHandler evt = new EventHandler(); Thread looper; boolean keepGoing = true; public void init(){ //get the kite images kite[NORTH] = getImage (getDocumentBase(), "kiteN.gif"); kite[NORTHEAST] = getImage (getDocumentBase(), "kiteNE.gif"); kite[EAST] = getImage (getDocumentBase(), "kiteE.gif"); kite[SOUTHEAST] = getImage (getDocumentBase(), "kiteSE.gif"); kite[SOUTH] = getImage (getDocumentBase(), "kiteS.gif"); kite[SOUTHWEST] = getImage (getDocumentBase(), "kiteSW.gif"); kite[WEST] = getImage (getDocumentBase(), "kiteW.gif"); kite[NORTHWEST] = getImage (getDocumentBase(), "kiteNW.gif"); this.setBackground(new Color(232, 232, 255)); this.addKeyListener(evt); this.requestFocus(); } // end init public void start(){ if (looper == null){ looper = new Thread(this); keepGoing = true; looper.start(); } // end if } // end start public void stop(){ keepGoing = false; looper = null; } // end stop public void run(){ while (keepGoing){ try { looper.sleep(100); } catch (InterruptedException exc){ System.out.println(exc.getMessage()); } // end try switch (direction){ case NORTH: dx = 0; dy = -10; break; case NORTHEAST: dx = 7; dy = -7; break; case EAST: dx = 10; dy = 0; break; case SOUTHEAST: dx = 7; dy = 7; break; case SOUTH: dx = 0; dy = 10; break; case SOUTHWEST: dx = -7; dy = 7; break; case WEST: dx = -10; dy = 0; break; case NORTHWEST: dx = -7; dy = -7; break; } // end switch x += dx; if (x < 0){ x = 0; } // end if int appWidth = this.getSize().width; appWidth -= (kite[direction].getWidth(this)/4); if (x > appWidth){ x = appWidth; } // end if y += dy; if (y < 0){ y = 0; } // end if int appHeight = this.getSize().height; appHeight -= (kite[direction].getHeight(this)/4); if (y > appHeight){ y = appHeight; } // end if repaint(); } // end while } // end run public void paint(Graphics g){ g.drawImage(kite[direction], x, y, 25, 25, this); } // end paint private class EventHandler extends KeyAdapter { public void keyPressed(KeyEvent e){ if (e.getKeyCode() == KeyEvent.VK_LEFT){ direction--; if (direction < NORTH) { direction = NORTHWEST; } // end if } else if (e.getKeyCode() == KeyEvent.VK_RIGHT){ direction++; if (direction > NORTHWEST){ direction = NORTH; } // end if } // end key checking if } // end key press event } // end eventHandler class def } // end kite class def