// Fly-swatting game import java.awt.*; import java.applet.*; import java.awt.event.*; public class Fly extends Applet implements Runnable { Thread anim; int fly_x, fly_y; boolean fly_alive = true; int swatter_x, swatter_y; public void init() { fly_x = 200; fly_y = 150; swatter_x = 350; swatter_y = 250; mseL ml = new mseL(); addMouseListener(ml); addMouseMotionListener(ml); setBackground(Color.cyan); } public void start() { anim = new Thread(this); anim.start(); } public void stop() { anim=null; } public void run() { while(anim != null) { updateFly(); repaint(); try{ Thread.sleep(1000); } catch (Exception e) {} } } public void updateFly() { int dx = (int)(20*Math.random()-10); int dy = (int)(20*Math.random()-10); fly_x += dx; fly_y += dy; // If offscreen, move back to center if (fly_x < 0 || fly_x > 400 || fly_y < 0 || fly_y > 300) { fly_x = 200; fly_y = 150; } } public void paint(Graphics g) { if (fly_alive) { g.setColor(Color.black); g.fillOval(fly_x-5, fly_y-5, 10, 10); } g.setColor(Color.red); g.drawRect(swatter_x-15, swatter_y-15, 30, 30); } class mseL extends MouseAdapter implements MouseMotionListener { public void mousePressed(MouseEvent e) { int x = e.getX(); int y = e.getY(); if (x-15 < fly_x && fly_x < x+15 && y-15 < fly_y && fly_y < y+15) { // Fly is killed fly_alive = false; } } public void mouseMoved(MouseEvent e) { int x = e.getX(); int y = e.getY(); swatter_x = x; swatter_y = y; repaint(); } public void mouseDragged(MouseEvent e){} } }