//スカッシュゲーム //跳ね返るボールをマウスで打ち返す import java.applet.*; import java.awt.*; import java.awt.event.*; /**/ public class Squash extends Applet implements Runnable,MouseMotionListener{ int fWidth,fHeight;//ゲーム画面の幅、高さ int barX,barY;//バーの位置 int barWidth = 38;//バーの幅 int barHeight = 8;//バーの高さ int ballX,ballY;//ボールの位置 int ballD = 12; int ballR = ballD / 2;//ボールの直径と半径 int bVX,bVY;//ボールの速度 Thread thread; boolean runThread = false; public void init(){ //各種変数の初期設定 //アプレットのサイズからゲーム画面の幅を規定する fWidth = this.getWidth(); fHeight = this.getHeight(); //バーの位置 barY = fHeight - 36; barX = fWidth / 2 - (barWidth / 2);//これは以後固定 //ボールの位置 ballX = (int)(fWidth * Math.random()); ballY = (int)((fHeight / 2 - 16) *Math.random()); //ボールの速度 bVX = (int)(3+2 * Math.random()); //bVX = (Math.random() > 0.5)? bVX * -1: bVX;//50%の割合で反転 bVY = (int)(3+2 * Math.random()); // bVY = (Math.random() > 0.5)? bVY * -1: bVY;//同上 addMouseMotionListener(this);//マウスリスナーの追加 }//init public void start(){ //スレッド開始処理 runThread = true; thread = new Thread(this); thread.start();//run()で実行 }//start public void update(Graphics g){ //repeint()で clearRect()させないためにオーバーライド paint(g); }//update public void mouseMoved(MouseEvent me){ //マウスイベント if(runThread) barX = me.getX();//バーのX座標をマウスの座標にする // System.out.println("bar : " + barX); }//mouseMoved public void mouseDragged(MouseEvent me){ //マウスイベント 何もしない }//mouseDragged public void run(){ //スレッドでゲームの実行 while(runThread){ // System.out.println("thread running."); //ボールの位置を更新する //X方向 ballX += bVX; if(ballX - ballR < 0){ ballX = ballR; bVX = -bVX; }//if else if(ballX + ballR > fWidth){ ballX = fWidth - ballR; bVX = -bVX; }//else //Y方向 ballY += bVY; if(ballY - ballR < 0){ ballY = ballR; bVY = -bVY; }//if else if(ballY + ballR > fHeight){ runThread = false;//落下したら、スレッド停止 }//else //ボールとバーの接触判定 if(ballX >= barX - ballR && ballX <= barX + barWidth + ballR && ballY >= barY - ballR && ballY <= barY + 4){ ballY = barY - ballR ; bVY = -bVY; //x方向の速度を乱数で変化 bVX = bVX + (int)(4 * Math.random())-2; }//if hit try{ //ボールの速さを設定 Thread.sleep(33);//遅延 }//try catch(Exception e){ System.out.println(e); }//catch repaint();//再描画 }//while }//run public void paint(Graphics g){ //描画 //背景 g.setColor(new Color(192,224,255)); g.fillRect(0,0,fWidth,fHeight); //バー g.setColor(new Color(64,96,128)); g.fillRect(barX,barY,barWidth,barHeight); //ボール g.fillOval(ballX - ballR,ballY - ballR,ballD,ballD); }//paint }//Squash