跳到主要內容

java打地鼠


一、設計心得


1.利用java的Button元件來進行遊戲的變化,首先以網格配置方式來填裝Button(建置n*n的地圖大小)。
2.匯入圖片及音效、背景音樂來增加遊戲樂趣(音效以AudioClip進行播放、圖片則以ImageIcon變化)。
3.設計TimeClock介面進行時間控制。
4.設計一Thread介面來進行圖片的更換及時間的減少。
5.定義命中的分數、打到炸彈的扣分、打中時鐘則加時間等規則來增加耐玩度。

二、遊戲DEMO


三、原始碼

1.HitMouse_Applet.java
import java.applet.AudioClip;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class HitMouse_Applet extends JApplet implements ActionListener,MouseListener{
    private Cursor cusRemondRelease;//自訂滑鼠圖案放開時
    private Cursor cusRemondPress;//自訂滑鼠圖案按下時
    Image RemondImgRelease = new ImageIcon(getClass().getResource("picture/hammer.png")).getImage();
    Image RemondImgPress = new ImageIcon(getClass().getResource("picture/hammerDown.png")).getImage();
    private JPanel jpNorth = new JPanel(new FlowLayout());
    private JPanel jpCenter = new JPanel();
    private JPanel jpSouth = new JPanel(new FlowLayout());
    private JButton jbStart = new JButton();
    private JButton jbQuestion = new JButton();
    private JButton jbGame[];//配置按鈕
    private JComboBox comMap = new JComboBox();
    private JLabel jlTime = new JLabel("剩餘時間:30秒");//時間倒數
    private JLabel jlScore = new JLabel();//分數
    private int iLattice = 5;//Width & Height
    private int iTime = 30*1000;//30秒
    private ImageIcon iConMouse = new ImageIcon(getClass().getResource("picture/Mouse.png"));//Mouse圖片
    private ImageIcon iConBomb = new ImageIcon(getClass().getResource("picture/Bomb.png"));//Bomb圖片
    private ImageIcon iConTime = new ImageIcon(getClass().getResource("picture/time.png"));//Bomb圖片
    private ImageIcon iConBombing = new ImageIcon(getClass().getResource("picture/Bombing.jpg"));//Bombing圖片
    private ImageIcon iConWin = new ImageIcon(getClass().getResource("picture/Winner.jpg"));
    private ImageIcon iConGood = new ImageIcon(getClass().getResource("picture/GoodJob.jpg"));
    private ImageIcon iConText = new ImageIcon(getClass().getResource("picture/Answer.png"));
    private TimeThread_Applet timethread = null;
    private int iScore = 0;//分數
    private Color c;//預設按鈕顏色
    private AudioClip bombAudio,hitAudio,backAudio,timeAudio;
    public void init(){
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screenSize = toolkit.getScreenSize();
        int screenHeight = (int) screenSize.getHeight();// 解析度長
        int screenWidth = (int) screenSize.getWidth();// 解析度寬        
        this.getContentPane().setBackground(Color.CYAN);
        this.setSize(800,600);
        this.setLocation(screenWidth / 2 - this.getWidth() / 2, screenHeight / 2
    -   this.getHeight() / 2);// 設定Frame置中         
        cusRemondRelease = this.getToolkit().createCustomCursor(RemondImgRelease, new Point(16,16), "Tand");//自訂滑鼠圖案
        this.setCursor(cusRemondRelease);
        getjpNorth();
        getjpCenter();
        getjpSouth();
        this.add(jpNorth,BorderLayout.NORTH);  
        this.add(jpCenter,BorderLayout.CENTER);
        this.add(jpSouth,BorderLayout.SOUTH);  
        bombAudio = getAudioClip(getCodeBase(), "audio/bomb.wav"); 
        hitAudio = getAudioClip(getCodeBase(), "audio/hit.wav"); 
        backAudio = getAudioClip(getCodeBase(), "audio/back.mid"); 
        timeAudio = getAudioClip(getCodeBase(), "audio/time.wav"); 
        this.setVisible(true);
    }
     private void getjpNorth() {
        jbStart.addActionListener(this);
        jbStart.setPreferredSize(new java.awt.Dimension(32, 32));
        jbStart.setIcon(new ImageIcon(getClass().getResource("picture/start.png")));
        jbQuestion.addActionListener(this);
        jbQuestion.setPreferredSize(new java.awt.Dimension(32, 32));
        jbQuestion.setIcon(new ImageIcon(getClass().getResource("picture/Question.png")));
        DefaultComboBoxModel com = new DefaultComboBoxModel();
        com.addElement("地圖一");
        com.addElement("地圖二");
        com.addElement("地圖三");
        comMap.setModel(com);
        comMap.addActionListener(this);
        jpNorth.add(comMap);     
        jpNorth.add(jbStart);
        jpNorth.add(jbQuestion);
    }
    private void getjpCenter() {               
        ButtonInit();      
    }
    private void ButtonInit() {
        jpCenter.removeAll();
        if (comMap.getSelectedIndex() == 0){
            iLattice = 5;
            c =Color.BLUE;
        }else if (comMap.getSelectedIndex() == 1){
            iLattice = 6;
            c =Color.YELLOW;
        }else if (comMap.getSelectedIndex() == 2){
            iLattice = 7;
            c =Color.WHITE;
        }
        jbGame = new JButton[iLattice*iLattice];
        jpCenter.setLayout(new GridLayout(iLattice,iLattice));
          for (int i = 0; i < iLattice*iLattice; i++) {
            jbGame[i] = new JButton();
            jbGame[i].setBackground(c); 
            jbGame[i].addMouseListener(this);
            jpCenter.add(jbGame[i]);
        }
          this.validate();
    }
    private void Check(JButton jb) {      
        for (int i = 0; i < jbGame.length; i++) {
            if (jb == jbGame[i]){
                int nowTime = getTimeThread().getTime();
                if (jb.getIcon() == iConMouse) {
                    hitAudio.play();
                    jbGame[i].setIcon(null);
                    jbGame[i].setText("Hit"); 
                    jbGame[i].setBackground(Color.red);
                    iScore += 10;
                }else if (jb.getIcon() == iConBomb){
                    bombAudio.play();
                    getTimeThread().setTime(nowTime - 4000);//打到炸彈-4秒
                    jbGame[i].setIcon(iConBombing);
                    iScore -= 20;
                }else if (jb.getIcon() == iConTime){
                    timeAudio.play();
                    int addTime = (int)(Math.random()*3);
                    getTimeThread().setTime(nowTime + addTime*1000);//打到時鐘+0~2秒
                    jbGame[i].setIcon(null);
                    jbGame[i].setText("Time + " + addTime); 
                    jbGame[i].setBackground(Color.MAGENTA);
                }
                jlScore.setText("目前分數:" + (iScore));
            }        
        }
    }
    private void getjpSouth() {
        jpSouth.add(jlTime);
        jpSouth.add(jlScore);
    }    
    private void Start() {
        iScore = 0;
        jlScore.setText("目前分數:" + iScore);
        getTimeThread().setTime(iTime);
        getTimeThread().setStart();
        jbStart.setEnabled(false);
        comMap.setEnabled(false);
        Thread t = new Thread(getTimeThread());
        t.start();   
        backAudio.loop();
    }
     public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbStart) Start();
        else if (e.getSource() == comMap) ButtonInit();
        else if (e.getSource() == jbQuestion) Answer();
    }
    private TimeThread_Applet getTimeThread() {
        if (timethread == null) {
            timethread = new TimeThread_Applet();
            timethread.init(this);
        }
        return timethread;
    }//由TimeThread.java觸發
    public void setTime(String s){jlTime.setText("剩餘時間:" + s + "秒");}
    public void CreateRandom(String s){//由TimeThread.java觸發 
        int mouseElements = Math.abs(Integer.valueOf(s)%4);//產生0~3個目標物    
        int bombElements = Math.abs(Integer.valueOf(s)%7);//產生0~7個炸彈
        int timeElements = Math.abs((Integer.valueOf(s)%2));//產生0~1個時鐘
        int r;
        for (int i = 0; i < timeElements; i++) {//產生亂數
            r = (int) (Math.random()*iLattice*iLattice);       
            this.jbGame[r].setIcon(iConTime);//亂數產生Mouse圖片
        }
        for (int i = 0; i < mouseElements; i++) {//產生亂數
            r = (int) (Math.random()*iLattice*iLattice);       
            this.jbGame[r].setIcon(iConMouse);//亂數產生Mouse圖片
        }
        for (int i = 0; i < bombElements; i++) {
            r = (int) (Math.random()*iLattice*iLattice);
            this.jbGame[r].setIcon(iConBomb); //亂數產生Bomb圖片
        }
    }
    public void ClearIcon(){//由TimeThread.java觸發 
        for (int i = 0; i < iLattice*iLattice; i++) {
            this.jbGame[i].setIcon(null);//清除圖片
            this.jbGame[i].setText("");          
            this.jbGame[i].setBackground(c);
        }
    }
    public void GameOver(){//由TimeThread.java觸發 
        jbStart.setEnabled(true);
        comMap.setEnabled(true);
        if (iScore >= 500)
        JOptionPane.showMessageDialog(this, "你所得分數為:" + iScore + "\n非常厲害","得分",JOptionPane.INFORMATION_MESSAGE,iConWin);        
        else if (iScore >=300 && iScore < 500) 
        JOptionPane.showMessageDialog(this, "你所得分數為:" + iScore + "\n很有前途,再接再厲","得分",JOptionPane.INFORMATION_MESSAGE,iConGood);
        else if (iScore < 300) 
        JOptionPane.showMessageDialog(this, "你所得分數為:" + iScore + "\n要多加油囉!!!","得分",JOptionPane.INFORMATION_MESSAGE,iConBombing);        
        backAudio.stop();
    }    
    private void Answer(){
         JOptionPane.showMessageDialog(this, "", "說明", JOptionPane.INFORMATION_MESSAGE, iConText);
    }
    public void mouseClicked(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {
        cusRemondPress = this.getToolkit().createCustomCursor(RemondImgPress, new Point(16,16), "Tand");//自訂滑鼠圖案
        this.setCursor(cusRemondPress);  
        JButton jb = (JButton) e.getSource();
        Check(jb);   
    }
    public void mouseReleased(MouseEvent e) {
        cusRemondRelease = this.getToolkit().createCustomCursor(RemondImgRelease, new Point(16,16), "Tand");//自訂滑鼠圖案
        this.setCursor(cusRemondRelease);
    }
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}       
  
}
2.TimeThread_Applet.java
public class TimeThread_Applet implements java.lang.Runnable{
    private HitMouse_Applet hit = null;
    private TimeClock tc = null;  
    public void setStop(){this.tc.Stop();}
    public void setStart(){this.tc.Start();}
    public void setTime(int s){this.tc.setTime(s);}
    public int getTime(){return this.tc.getTimes();}
    public void init(HitMouse_Applet hit){
        this.hit = hit;
        tc = new TimeClock();
    }   
    public void run() {
        while (this.tc.isStop() == false){
            this.hit.CreateRandom(this.tc.getTime());
            this.tc.toDown();
            this.hit.setTime(this.tc.getTime());
            try {Thread.sleep(1000);}
            catch (InterruptedException ex) {System.out.println(ex.getMessage());}                  
            this.hit.ClearIcon();                                
         }
        hit.GameOver();
    }
}
3.TimeClock.java
public class TimeClock {
    private int t = 0;
    private boolean stop = false;
    public void setTime(int t){this.t = t;}//設定時間
    public String getTime(){return this.t/1000 + "";}//取得時間字串
    public int getTimes(){return t;}
    public boolean isStop(){return this.stop;}//確認是否停止
    public void Stop(){this.stop = true;}//停止
    public void Start(){this.stop = false;}//開始
    public void toDown(){      
        if (this.stop) return;
        if (t > 0){
            t -=1000;
        }else this.stop = true;
    }
}

留言

這個網誌中的熱門文章

java西元民國轉換_各種不同格式

C#資料庫操作(新增、修改、刪除、查詢)

【Excel好好玩】 自己的資產自己管!善用Google Sheet來幫我們評估貸款

這次介紹的主題是關於Excel的貸款還款計畫試算,我們人生中總會遇到需要大筆金額的花費,但當資金不夠時就得進行貸款,而貸款之前如果我們能夠審慎評估,並分析自己的還款能力之後在進行凍作,相信風險會小很多,因此就自己動動手來使用Google Sheet進行試算吧! 基本資料 ● 貸款總額: 1000000 ● 貸款期數: 84月 ● 年利率: 2.11% ● 月利率: 0.18% P.S 月利率 = 年利率 / 12 重要函式 PMT : 這是Google Sheet內建的重要年金計算公式,我們可以善用這個公式來計算固定利率及期數的固定攤還本息。因為PMT函式計算出的結果為負數,所以前面加上-號轉成正數。 動手做 首先我們在Excel表上列出我們的基本資料 圖片來源 其中月利率的部分就使用公式「=B4/12」 接著我們填上第一列的期數跟餘額 圖片來源 =B2 =B3 使用關鍵PMT函數來計算本息的部分 因為PMT函式計算出的結果為負數,所以前面加上-號轉成正數。 -PMT(貸款利率(月利率), 貸款期數, 貸款總額) =-PMT($B$5,$B$3,$B$2) 圖片來源 計算利息 利息 = 貸款餘額 x 月利率 =B8*$B$5 圖片來源 計算本金 本金 = 本息 - 利息 =C8-D8 圖片來源 製作第二列餘額的部分 餘額的部分 = 上一期的餘額 - 上一期的本金 圖片來源 接著拖曳該兩列往下拉,即可查看每一期的利息與本金 圖片來源 結語 雖然市面上已經有很多貸款銀行都提供了試算功能,但如果我們想要進一步管理自己的資產時,就需要將每一期的金額給計算出來,因此才會將公式運用在Excel表,讓我們的資產管理表能夠結合負債,進一步評估我們理財行動的下一步,希望這樣的經驗可以幫助到正在理財道路上打拼的夥伴,讓我們透過有效的管理,幫助荷包長大吧! 喜歡撰寫文章的你,不妨來了解一下: Web3.0時代下為創作者、閱讀者打造的專屬共贏平台 — 為什麼要加入? 歡迎加入一起練習寫作,賺取知識,累積財富!