rep14ans

rep14ans



動作内容
アプレット領域内の任意の位置にボールを任意の方向に射出し,壁で跳ね返るように動かし続ける.
プログラム
/*--------------------------------------------
 rep14ans.java
 ボールを転がそう(初期位置・射出方向ランダム)
 作成者:堀田
 ---------------------------------------------*/
import java.applet.*;
import java.awt.*;
import java.util.Random;

public class rep14ans extends Applet implements Runnable{
	Thread thd = null;
	Dimension size;
	Random rnd;
	int x, y, vel, app_wid, app_hei, dia;
	double theta;

	public void init() {    // 初期化処理
		size = getSize();		// アプレット画面の大きさ取得
		app_wid = size.width; app_hei = size.height;
		dia = 50;				// 描画ボールの直径(diameter)
		vel = 10;				// 描画ボールの速度(velocity)
		rnd = new Random();
		x = rnd.nextInt(app_wid-dia); y = rnd.nextInt(app_hei-dia);	// 描画ボールの初期位置(x, y)
		theta = Math.PI / rnd.nextInt(13);	// 描画ボールの射出方向(π/6)
		thd = new Thread(this);
		thd.start();
	}
	public void update(Graphics g) {    // 再描画で背景クリアをしない
		paint(g);
	}

	public void paint(Graphics g) { // 描画処理
		g.setColor(Color.blue);
		g.drawOval(x, y, dia, dia);
	}

	public void run() {     // 実行処理
		while (true) {
			if (0 < x && x < app_wid-dia && 0 < y && y < app_hei-dia) {
			//	theta = theta;
			} else if (y <= 0 || y >= app_hei-dia) {
				theta = 2*Math.PI - theta;
			} else if (x <= 0 || x >= app_wid-dia) {
				if (0 <= theta && theta < Math.PI) {
					theta = Math.PI - theta;
				} else if (Math.PI <= theta && theta <= 2*Math.PI) {
					theta = 3*Math.PI - theta;
				}
			} else {
				System.out.println("Error: theta...");
			}
			double dx = vel * Math.cos(theta);
			double dy = vel * Math.sin(theta);
			x += dx;
			y += dy;

			repaint();

			try {
				thd.sleep(10);
			} catch (InterruptedException e) {
			}
		}
	}
}