Java用集合實現斗地主發牌


本文以java雙列集合HashMap為核心實現發牌操作:                               

思路:

1.准備牌:創建一個Map集合,存儲牌的索引和組裝好的牌

     創建一個list集合,來儲存牌的索引。

     定義一個花色數組和牌的點數大小的數組,雙重for循環來組裝牌,大小王單獨存入集合

2.洗牌:Colletions中的shuffle(List)方法來打亂牌的順序

3.發牌:定義4個集合,存儲玩家牌的索引和底牌的索引, 遍歷存儲牌索引的List集合,獲取每一個牌的索引

4.排序:使用Collections中的方法sort(List)默認是升序排序

5.看牌:定義一個lookpoker()方法

 

代碼:

    public static void main(String[] args) {
        //存撲克
        HashMap<Integer, String> poker = new HashMap<>();
        //存撲克牌的索引
        ArrayList<Integer> pokerIndex = new ArrayList<>();
        //通過循環遍歷組裝牌;
        String[] colors = {"♠","♥","♣","♦"};
        String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        int index = 0;
        poker.put(index, "大王");
        pokerIndex.add(index++);
        poker.put(index, "小王");
        pokerIndex.add(index++);
 //循環嵌套遍歷兩個數組,組裝52張牌,存儲到集合中
for (String number : numbers) { for (String color : colors) { poker.put(index, color + number); pokerIndex.add(index++); } } // System.out.println(poker);
      //打亂牌的順序 Collections.shuffle(pokerIndex); // System.out.println(pokerIndex); ArrayList<Integer> play1 = new ArrayList(); ArrayList<Integer> play2 = new ArrayList(); ArrayList<Integer> play3 = new ArrayList(); ArrayList<Integer> dipai = new ArrayList(); for (int i = 0; i < pokerIndex.size(); i++) { if (i >= 51) { dipai.add(pokerIndex.get(i)); } else if (i % 3 == 0) { play1.add(pokerIndex.get(i)); } else if (i % 3 == 1) { play2.add(pokerIndex.get(i)); } else { play3.add(pokerIndex.get(i)); } }       
// 使用Collections中的方法sort(List)默認是升序排序
        Collections.sort(dipai);
        Collections.sort(play1);
        Collections.sort(play2);
        Collections.sort(play3);

        lookPoker("賭聖", poker, play1);
        lookPoker("賭俠", poker, play2);
        lookPoker("賭神", poker, play3);
        lookPoker("底牌", poker, dipai);
    }

    /*
        定義一個看牌的方法,提高代碼的復用性
        參數:
            String name:玩家名稱
            HashMap<Integer,String> poker:存儲牌的poker集合
            ArrayList<Integer> list:存儲玩家和底牌的List集合
        查表法:
             遍歷玩家或者底牌集合,獲取牌的索引
             使用牌的索引,去Map集合中,找到對應的牌
     */
    public static void lookPoker(String name, HashMap<Integer, String> poker, ArrayList<Integer> list) {
        //輸出玩家名稱,不換行
        System.out.print(name + ":");
        //遍歷玩家或者底牌集合,獲取牌的索引
            for (Integer key : list) {
            //使用牌的索引,去Map集合中,找到對應的牌
            String value = poker.get(key);
            System.out.print(value + " ");
        }
        System.out.println();//打印完每一個玩家的牌,換行
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM