/*----------------------------------- ex13_5.java イベント処理:もぐらたたき(完成版) ------------------------------------*/ import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.Random; /* */ public class ex13_5 extends Applet implements Runnable, MouseListener { Thread thd = null; int bx[] = {60, 180, 300}, by[] = {70, 170, 270}, cnt, x, y; boolean flg = false; // もぐら出現フラグ boolean hit = false; // もぐらたたき成功フラグ String msg; Random rnd; public void init() { // 初期化処理 msg = ""; cnt = 0; x = 0; y = 0; thd = new Thread(this); thd.start(); rnd = new Random(); addMouseListener(this); // マウスイベントを自クラスで受け取る宣言 } public void paint(Graphics g) { // 描画処理 g.setFont(new Font("Dialog", Font.PLAIN, 20)); g.setColor(Color.red); g.drawString(msg, 10, 25); g.setColor(Color.green); // 背景:芝生 g.fillRect(0, 30, 400, 370); g.setColor(Color.black); // 背景:穴 g.fillOval( 50, 100, 70, 30); g.fillOval(170, 100, 70, 30); g.fillOval(290, 100, 70, 30); g.fillOval( 50, 200, 70, 30); g.fillOval(170, 200, 70, 30); g.fillOval(290, 200, 70, 30); g.fillOval( 50, 300, 70, 30); g.fillOval(170, 300, 70, 30); g.fillOval(290, 300, 70, 30); if (cnt >= 10) { // 10匹退治したらゲーム終了 g.setColor(Color.magenta); g.drawString("Congratulations!", 100, 200); } else { if (flg == true && hit == false) { // モグラ出現 & まだたたいてない x = bx[rnd.nextInt(3)]; // モグラ出現位置 x座標(ランダム) y = by[rnd.nextInt(3)]; // モグラ出現位置 y座標(ランダム) g.setColor(Color.yellow); // モグラ:体 g.fillRoundRect(x, y, 50, 55, 30, 30); g.setColor(Color.black); g.fillOval(x+15, y+12, 10, 15); // モグラ:左目 g.fillOval(x+35, y+10, 10, 15); // モグラ:右目 g.setColor(Color.red); g.fillOval(x+30, y+30, 12, 10); // モグラ:鼻 } else if (flg == true && hit == true) { // モグラ出現 & たたくの成功 g.setColor(Color.yellow); // モグラ:体 g.fillRoundRect(x, y, 50, 55, 30, 30); g.setColor(Color.black); g.drawLine(x+10, y+10, x+40, y+25); // モグラ:左目(バッテン) g.drawLine(x+10, y+25, x+40, y+10); // モグラ:右目(バッテン) g.setColor(Color.red); g.fillOval(x+30, y+30, 12, 10); // モグラ:鼻 } } } public void run() { while (cnt < 10) { // 10匹退治するまでループ double tmp = rnd.nextDouble(); if (tmp < 0.3) { // 30%の確率でモグラ出現 flg = true; // モグラ出現フラグON(true) } else { flg = false; // モグラ出現フラグOFF(false) } if (hit == true) { // たたくのに成功していたら… hit = false; // ヒット成功フラグをOFFに } try { thd.sleep(1000); } catch (InterruptedException e) { } repaint(); } repaint(); } public void mouseClicked(MouseEvent e) { // マウスクリック時の処理 Point pt = e.getPoint(); // マウスクリック位置取得 if (flg == true && hit == false && x <= pt.x && pt.x <= x+50 && y <= pt.y && pt.y <= y+50) { cnt++; msg = "Hit! : " + cnt + "匹退治! 残り" + (10-cnt) + "匹"; hit = true; // モグラたたき成功フラグON(true) } repaint(); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} }