1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| package com.fluffysponge; /* * 需求: * 通过程序实现斗地主过程中的洗牌,发牌和看牌。要求:对牌进行排序 * 思路: * 1.创建HashMap,键是编号,值是牌 * 2.创建ArrayList,存储编号 * 3.创建花色数组和点数数组 * 4.从0开始往HashMap里面存储编号,并存储对应的牌,同时往ArrayList里面存储编号 * 5.洗牌(洗的也是编号),用Collections的shuffle()方法实现 * 6.发牌(发的也是编号,为了保证编号是排序的,创建了TreeSet集合接收) * 7.定义方法看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌) * 8.调用看牌方法 * * */
import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet;
public class PokerDemo { public static void main(String[] args) { //创建HashMap,键是编号,值是牌 HashMap<Integer, String> hm = new HashMap<>();
//创建ArrayList,存储编号 ArrayList<Integer> array = new ArrayList<>();
//创建花色数组和点数数组 String[] colors = {"♦", "♠", "♣", "♥"}; String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
//从0开始往HashMap里面存储编号,并存储对应的牌,同时往ArrayList里面存储编号 int index = 0; for (String number : numbers) { for (String color : colors) { hm.put(index, color + number); array.add(index); index++; } } hm.put(index, "小王"); array.add(index); index++; hm.put(index, "大王"); array.add(index); index++;
//洗牌(洗的也是编号),用Collections的shuffle()方法实现 Collections.shuffle(array);
//发牌(发的也是编号,为了保证编号是排序的,创建了TreeSet集合接收) TreeSet<Integer> zsSet = new TreeSet<>();//张三 TreeSet<Integer> lsSet = new TreeSet<>();//李四 TreeSet<Integer> wwSet = new TreeSet<>();//王五 TreeSet<Integer> dpSet = new TreeSet<>();//底牌 for (int i = 0; i < array.size(); i++) { int x = array.get(i); if (i >= array.size() - 3) { dpSet.add(x); } else if (i % 3 == 0) { zsSet.add(x); } else if (i % 3 == 1) { lsSet.add(x); } else if (i % 3 == 2) { wwSet.add(x); } }
//调用看牌方法 lookPorker("张三", zsSet, hm); lookPorker("李四", lsSet, hm); lookPorker("王五", wwSet, hm); lookPorker("底牌", dpSet, hm);
}
//定义方法看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌) public static void lookPorker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) { System.out.print(name + "的牌是:"); for (Integer key : ts) { String poker = hm.get(key); System.out.print(poker + " "); } System.out.println(); } }
|