/* Program: MoveBall Class Purpose: Ball‚đ“®‚©‚· @author segi.tetsu@ss.bch.ntt.jp @version 1.00; 20 Mar 1996 */ import java.util.Random; import java.applet.Applet; import java.applet.AudioClip; import java.awt.*; public class MoveBall extends Applet implements Runnable { static final int r = 30; int x = r + 1; int y = 125; int movex = 3; int movey = 3; int color = 0; AudioClip au; Thread thread; Image off_im; Graphics off_g; public void init() { String audiofile = null; String s; s = getParameter("audiofile"); if (s != null) audiofile = s; au = getAudioClip(getDocumentBase(), audiofile); resize(600, 250); setBackground(Color.blue); if (off_g == null) { off_im = this.createImage(600, 250); off_g = off_im.getGraphics(); } } public void start() { if (thread == null) { thread = new Thread(this); thread.start(); } } public void stop() { if (thread != null) { thread.stop(); thread = null; } } public void update(Graphics g) { off_g.setColor(getBackground()); off_g.fillRect(0, 0, size().width, size().height); switch(color) { case 0: off_g.setColor(Color.yellow); break; case 1: off_g.setColor(Color.magenta); break; case 2: off_g.setColor(Color.orange); break; case 3: off_g.setColor(Color.pink); break; case 4: off_g.setColor(Color.red); break; case 5: off_g.setColor(Color.white); break; default: break; } off_g.fillOval(x, y, r, r); g.drawImage(off_im, 0, 0, this); } public void run() { Random aRandom = new Random(); int sign; while(true) { try { Thread.sleep(0); } catch (InterruptedException e) { break; } if (x <= 0 && movex < 0) { movex = aRandom.nextInt() % 5; if (movex < 0) movex = -movex; if (movex == 0) movex = 1; if (movey > 0) { sign = 1; } else { sign = -1; } movey = aRandom.nextInt() % 5 + 1; if (sign * movey < 0) movey = -movey; repaint(); au.play(); color++; } if (x >= 600 - r && movex > 0) { movex = -movex; au.play(); } if ((y <= 0 && movey < 0) || (y >= 250 - r && movey > 0)) { movey = -movey; au.play(); } x += movex; y += movey; if (color > 5) color = 0; repaint(); } } }