Java實現擲骰子控制檯和窗體兩種實現方法

程序目標:同時3擲骰子,讓骰子轉動若干次後停下來的正面朝上的數字之和大於9 則爲大,小於等於9則爲小
用於需要提前選擇押大還是小,程序結束返回是否押中的結果。

1.擲骰子控制檯實現
本程序分爲三層:表示層 :用類Player2 實現
                                業務邏輯層:類DiceGame2 實現
                                數據/技術服務層:類Dice2 實現
Dice2 類 實現Runnable接口,重新run()方法來設置每個骰子轉動10次 ,並在停下來後獲取正面朝上的值。
DiceGame2  類中創建三個線程來模擬同時擲3個骰子,並能在在骰子轉動結束後得到總點數和每個骰子的點數。
其中roll()方法開啓線程,  result()計算點數
Player2 類 主函數創建菜單,提示用戶輸入操作。並在控制檯顯示結果。

 代碼如下:

public class Player2 {  //表示層
	public static void main(String[] args) throws InterruptedException {		
		Scanner sc = new Scanner(System.in);
		while (true) {
			System.out.println("**************擲 骰 子 遊 戲***************");
			System.out.println("請輸入0表示押小,輸入1表示押大,輸入2表示退出");
			int i = sc.nextInt();
			if(i == 2)
				System.exit(0);
			
			DiceGame2 d = new DiceGame2();
			d.roll();
			Thread.sleep(500);// 主線程等待
	
			int n = d.result();
			if (i == 0 && n <= 9)
				System.out.println("恭喜你,押小贏了");
			else if (i == 0 && n > 9)
				System.out.println("很遺憾,押小輸了");
			else if (i == 1 && n > 9)
				System.out.println("恭喜你,押大贏了");
			else if (i == 1 && n <= 9)
				System.out.println("很遺憾,押大輸了");				
			System.out.println();	
		}
	}
}

class DiceGame2 {  //業務邏輯層
	Dice2 d1, d2, d3;

	public DiceGame2() {
	}

	public void roll() { // 同時三個擲骰子

		d1 = new Dice2();
		d2 = new Dice2();
		d3 = new Dice2();
		Thread t1 = new Thread(d1);
		Thread t2 = new Thread(d2);
		Thread t3 = new Thread(d3);
		t1.start();
		t2.start();
		t3.start();

	}

	public int result() { // 計算點數
		int sum = 0;
		int i = d1.getUpNum();
		int j = d2.getUpNum();
		int k = d3.getUpNum();

		sum = i + j + k;

		System.out.println("擲得點數和爲:" + sum + " [" + i + " - " + j + " - " + k + " ]");
		return sum;
	}//
}

class Dice2 implements Runnable { // 骰子類  數據/技術服務層
	private int upnum;

	public Dice2() {
		this.upnum = 1;
	}

	@Override
	public void run() {
		int count = 10;// 設置每顆骰子轉動10次
		while (count > 0) {

			upnum = new Random().nextInt(6) + 1;
			System.out.println(Thread.currentThread().getName() + " " + upnum);

			count--;
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public int getUpNum() {
		return upnum;
	}
}

2.擲骰子窗體實現
窗體程序思路和控制檯一樣,只是把顯示界面由控制檯改爲窗體。
類SiziGame extends JFrame implements ActionListener
類IconThread implements Runnable
首先,SiziGame類通過構造器初始化設置窗體和裏面控件,並且把代表6種點數的圖片加載到imgs集合裏面,還要給開始按鈕綁定監聽事件函數。
其次,重寫actionPerformed()函數,來實現按鈕觸發3個骰子轉動。在這個函數裏開始3個線程讓骰子圖片轉動起來,並在轉動結束後計算機每個骰子顯示圖片對應的點數和總點數。再根據用戶之前選擇的押大或押小返回輸贏結果。
然後,IconThread 類重寫run()方法,來實現圖片的動態效果。通過隨機生成[0-6)的隨機整數作爲imgs集合的index,再根據索引從imgs裏取對應的圖片顯示在窗體上,由於線程運行速度較快,且設置了多次取圖片的動作從而形成了動態效果。注意的是集合下標爲[0-5],所以在SiziGame類中的result()方法計算點數時要+1。

public class SiziGame extends JFrame implements ActionListener{	
    private JLabel lb1;
    private JLabel lb2;
    private JLabel lb3;
    private JLabel lbNote;
    private JComboBox<String> cmb;
    private JButton btn;
    private JLabel labResult;    
    private static List<Icon> imgs = new ArrayList<Icon>();    
    IconThread it1,it2,it3;
    Thread t1,t2,t3;
    
    public static void main(String[] args) {
        new SiziGame();
    }
    
    public SiziGame(){
    	this.setLocationRelativeTo(null);
        this.setBounds(200, 50, 380, 297);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(null);
        this.setResizable(false);
               
        lb1 = new JLabel("");
        lb1.setIcon(new ImageIcon( getClass().getResource("img/a.jpg"))); 
        lb1.setBounds(30, 30, 96, 96);
        getContentPane().add(lb1);       

        lb2 = new JLabel("");
        lb2.setIcon(new ImageIcon( getClass().getResource("img/a.jpg")));
        lb2.setBounds(136, 30, 96, 96);
        getContentPane().add(lb2);

        lb3 = new JLabel("");
        lb3.setIcon(new ImageIcon( getClass().getResource("img/a.jpg")));
        lb3.setBounds(242, 30, 96, 96);
        getContentPane().add(lb3);
        
        lbNote = new JLabel("押");
        lbNote.setBounds(40, 200, 30, 30);
        getContentPane().add(lbNote);

        cmb = new JComboBox<String>();
        cmb.setBounds(80, 200, 60, 30);
        getContentPane().add(cmb);
        cmb.addItem("大");
        cmb.addItem("小");
        
        btn = new JButton("START");
        btn.setBounds(220, 190, 100, 50);
        btn.addActionListener(this);
        getContentPane().add(btn);
        
        labResult = new JLabel("結果"); //結果
        labResult.setBounds(136, 156, 126, 27);
        getContentPane().add(labResult);
        
        this.setVisible(true);
        
        imgs.add(new ImageIcon(getClass().getResource("img/1.gif")));
        imgs.add(new ImageIcon(getClass().getResource("img/2.gif")));
        imgs.add(new ImageIcon(getClass().getResource("img/3.gif")));
        imgs.add(new ImageIcon(getClass().getResource("img/4.gif")));
        imgs.add(new ImageIcon(getClass().getResource("img/5.gif")));
        imgs.add(new ImageIcon(getClass().getResource("img/6.gif")));
        
        it1 = new IconThread(lb1, imgs);         
        it2 = new IconThread(lb2, imgs);       
        it3 = new IconThread(lb3, imgs); 
        t1 = new Thread(it1);            
    	t2 = new Thread(it2); 
    	t3 = new Thread(it3);
        
    }//
       
    public void thread(){    	
    	/*IconThread it1 = new IconThread(lb1, imgs);         
	    IconThread it2 = new IconThread(lb2, imgs);       
	    IconThread it3 = new IconThread(lb3, imgs); 
	    
	    Thread t1 = new Thread(it1);            
	    Thread t2 = new Thread(it2); 
	    Thread t3 = new Thread(it3);*/

    	 it1 = new IconThread(lb1, imgs);         
	     it2 = new IconThread(lb2, imgs);       
	     it3 = new IconThread(lb3, imgs); 
	     t1 = new Thread(it1);            
		 t2 = new Thread(it2); 
		 t3 = new Thread(it3);
		 
		/* t1.start();
	     t2.start();
	     t3.start();
	        
        try {
			t1.join();
			t2.join();
			t3.join();
		} catch (InterruptedException e) {}*/
	           
    }        
    
	@Override
	public void actionPerformed(ActionEvent args) {
		String ya = cmb.getSelectedItem().toString();
	    System.out.println("\n你本次押的"+ya);
	       
	    thread();	
	     t1.start();
	     t2.start();
	     t3.start();
	        
       try {
			t1.join();
			t2.join();
			t3.join();
		} catch (InterruptedException e) {}
	              
        int i = result(lb1);
        int j = result(lb2);
        int k = result(lb3);
        int sum = i + j + k;
        System.out.println("擲得點數和爲:" + sum + " [" + i + " - " + j + " - " + k + " ]");
     
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {}
        
        if (sum > 9 && "大".equals(ya) || sum <= 9  && "小".equals(ya)) {               
            labResult.setText("贏");
            labResult.setForeground(Color.GREEN);
            labResult.setFont(new Font("宋體", Font.BOLD, 30));
        } 
        else {
            labResult.setText("輸");
            labResult.setForeground(Color.red);
            labResult.setFont(new Font("宋體", Font.BOLD, 30));
        }
	    
	}//
	
	public  int result(JLabel lab) {	        
	     Icon icon = lab.getIcon();// 獲取當前骰子圖片
	     int sum = 0;
	     for (int i = 0; i < imgs.size(); i++) {
	         if (icon.equals(imgs.get(i))) {   //取出和lab最後圖片對應的點數
	             sum += (i + 1);
	             break;
	         }
	     }
	     return sum;
	 }//      
}



希望和大家一起每天進步一點點!剛剛開始在公衆號同步博客,請大家多多支持,如有不足之處多多包含,最後多多關注哈哈哈。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章