1. 案例介紹
按照斗地主的規則,完成洗牌發牌的動作。
具體規則:
1. 組裝54張撲克牌
2. 將54張牌順序打亂
3. 三個玩家參與游戲,三人交替摸牌,每人17張牌,最后三張留作底牌。
4. 查看三人各自手中的牌(按照牌的大小排序)、底牌
l 手中撲克牌從大到小的擺放順序:大王,小王,2,A,K,Q,J,10,9,8,7,6,5,4,3
2. 案例需求分析
l 准備牌:
完成數字與紙牌的映射關系:
使用雙列Map(HashMap)集合,完成一個數字與字符串紙牌的對應關系(相當於一個字典)。
l 洗牌:
通過數字完成洗牌發牌
l 發牌:
將每個人以及底牌設計為ArrayList<String>,將最后3張牌直接存放於底牌,剩余牌通過對3取模依次發牌。
存放的過程中要求數字大小與斗地主規則的大小對應。
將代表不同紙牌的數字分配給不同的玩家與底牌。
l 看牌:
通過Map集合找到對應字符展示。
通過查詢紙牌與數字的對應關系,由數字轉成紙牌字符串再進行展示。
代碼實現:
1 import java.util.ArrayList; 2 import java.util.Collections; 3 import java.util.HashMap; 4 import java.util.List; 5 6 /** 7 * 實現模擬斗地主功能 8 * 1. 組合牌 9 * 2. 洗牌 10 * 3. 發牌 11 * 4. 看牌 12 * @author vanguard 13 * 14 */ 15 public class DouDiZhu { 16 public static void main(String[] args) { 17 //1. 組合牌 18 //創建Map集合,鍵是編號, 值是牌 19 HashMap<Integer, String> pooker = new HashMap<Integer, String>(); 20 //創建List集合存儲編號 21 List<Integer> pookerNum = new ArrayList<Integer>(); 22 //創建花色數組 23 String[] colors = {"♥", "♣", "♠", "♦"}; 24 //創建點數數組 25 String[] numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"}; 26 //定義整型數組,作為鍵出現 27 int index = 2; 28 //遍歷數組:花色+點數進行組合,存儲到Map集合中 29 for(String number : numbers) { 30 for(String color : colors) { 31 pooker.put(index, color + number); 32 pookerNum.add(index); 33 index++; 34 } 35 } 36 //存儲大王、小王到Map集合中 37 pooker.put(0, "大王"); 38 pookerNum.add(0); 39 pooker.put(1, "小王"); 40 pookerNum.add(1); 41 42 //2. 洗牌,將牌的編號打亂 43 Collections.shuffle(pookerNum); 44 45 //3. 發牌 46 //定義三個玩家和底牌集合 47 List<Integer> play1 = new ArrayList<Integer>(); 48 List<Integer> play2 = new ArrayList<Integer>(); 49 List<Integer> play3 = new ArrayList<Integer>(); 50 List<Integer> bottom = new ArrayList<Integer>(); 51 for(int i = 0; i < pookerNum.size(); i++) { 52 //先存底牌 53 if(i < 3) { 54 //存底牌 55 bottom.add(pookerNum.get(i)); 56 //對索引%3判斷 57 } else if(i % 3 == 0) { 58 //發給玩家1 59 play1.add(pookerNum.get(i)); 60 } else if(i %3 == 1) { 61 //發給玩家2 62 play2.add(pookerNum.get(i)); 63 } else if(i % 3 == 2) { 64 //發給玩家3 65 play3.add(pookerNum.get(i)); 66 } 67 } 68 //各個玩家的牌排序 69 Collections.sort(play1); 70 Collections.sort(play2); 71 Collections.sort(play3); 72 73 //4. 看牌 74 look("玩家1", play1, pooker); 75 look("玩家2", play2, pooker); 76 look("玩家3", play3, pooker); 77 look("底牌", bottom, pooker); 78 79 80 } 81 82 /** 83 * 看牌的方法 84 * 將玩家手中的編號,到Mpa集合中查找 85 * @param name 86 * @param play 87 * @param pooker 88 */ 89 private static void look(String name, List<Integer> play, HashMap<Integer, String> pooker) { 90 //遍歷ArrayList集合,獲取元素,作為鍵到Map集合中查找 91 System.out.print(name + ":"); 92 for(Integer key : play) { 93 String value = pooker.get(key); 94 System.out.print(value + " "); 95 } 96 System.out.println(); 97 } 98 }