java第一个案例:斗地主发牌(集合)
1 package cn.itcast.demo1; 2 3 import java.util.*; 4 5 public class Test7 { 6 public static void main(String[] args) { 7 // 1. 买牌 8 // 1.1 定义一个双列集合, 键:牌的编号 值:表示具体的牌 9 Map<Integer, String> pokers = new HashMap<>(); 10 // 1.2 定义一个单列集合用来存所有牌的编号 11 List<Integer> list = new ArrayList<>(); 12 13 // 1.3 具体的买牌动作 14 // 普通牌 52 15 String[] colors = {"♠", "♥", "♣", "♦"}; 16 String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; 17 int num = 0; 18 // 通过循环嵌套 19 for (String number : numbers) { 20 for (String color : colors) { 21 String poker = color + number; 22 pokers.put(num, poker); 23 list.add(num); 24 num++; 25 26 } 27 } 28 29 // 大小王 2 30 pokers.put(num, "小王"); 31 list.add(num++); 32 33 pokers.put(num, "大王"); 34 list.add(num); 35 36 // 打印牌就可以了 37 System.out.println("所有的牌:" + pokers); 38 System.out.println("牌的编号:" + list); 39 40 // 2. 洗牌 41 Collections.shuffle(list); 42 System.out.println("洗牌后的牌的编号:" + list); 43 44 // 3. 发牌 45 // 3.1 定义4个集合,表示三个玩家,底牌 46 List<Integer> player1 = new ArrayList<>(); 47 List<Integer> player2 = new ArrayList<>(); 48 List<Integer> player3 = new ArrayList<>(); 49 List<Integer> diPai = new ArrayList<>(); 50 51 // 3.2 具体的发牌动作,将索引和3取模,决定发给谁 52 for (int i = 0; i < list.size(); i++) { 53 Integer pokerNum = list.get(i); 54 if(i >= list.size()-3){ 55 diPai.add(pokerNum); 56 } 57 else if(i%3 == 0){ 58 player1.add(pokerNum); 59 } 60 else if(i%3 == 1){ 61 player2.add(pokerNum); 62 } 63 else if(i%3 == 2){ 64 player3.add(pokerNum); 65 } 66 67 } 68 69 // 3.3 查看玩家的牌 70 /* 71 System.out.println("player1 的牌: " + player1); 72 System.out.println("player2 的牌: " + player2); 73 System.out.println("player3 的牌: " + player3); 74 System.out.println("底牌: " + diPai); 75 */ 76 77 System.out.println("player1 的牌: " + printPoker(player1, pokers)); 78 System.out.println("player2 的牌: " + printPoker(player2, pokers)); 79 System.out.println("player3 的牌: " + printPoker(player3, pokers)); 80 System.out.println("底牌: " + printPoker(diPai, pokers)); 81 82 83 84 85 } 86 // 4. 定义一个方法看牌 87 public static String printPoker(List<Integer> nums, Map<Integer, String> pokers){ 88 // 1.对牌的编号进行顺序排列 89 Collections.sort(nums); 90 91 // 2. 遍历牌的编号集合,获取到每一个编号 92 StringBuilder sb = new StringBuilder(); 93 94 for (Integer num : nums) { 95 // 3. 根据编号去双列集合中查找该编号对应的具体的牌 96 String poker = pokers.get(num); 97 // 4. 将获取到的牌进行拼接 98 sb.append(poker + " "); 99 100 } 101 102 // 5. 将拼接后的结果返回即可 103 String str = sb.toString(); 104 return str.trim(); 105 106 107 } 108 }