每个步骤都有写注释,那就直接上代码吧。
public class Test3 {
public static void main(String[] args) {
//声明字符数组
String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] color = {"♠", "♥", "♦", "♣"};
//创建对象hmHashMap、ArrayList数组
HashMap<Integer, String> hmHashMap=new HashMap<>();//存储索引和牌
ArrayList<Integer> list = new ArrayList<>();//存储索引
//索引从0开始
int index=0;
//1.拼接牌色和索引存储到hmHashMap中
for (String s1 : num) {//外循环遍历牌号 每次循环生成4个牌色
for (String s2 : color) {//内循环遍历牌色 每次循环生成13张牌号
list.add(index);//每次牌对应的索引存储到list中
hmHashMap.put(index++, s2.concat(s1));//s2.concat(s1)将牌色+牌号 拼接成完整牌作为值。存入对应index索引,并且为下次索引号进行自加
}
}
//添加大小王牌到双列表集合中
hmHashMap.put(index, "小王");//小王的索引是52
list.add(index++);//将52添加到索引列表,之后自加得53。
hmHashMap.put(index, "大王");//大王的索引是53
list.add(index);//在将大王的索引53号添加到索引列表
//2.洗牌
Collections.shuffle(list);//(使用默认随机源对列表进行置换)
//3.发牌 创建有序集合 方便牌的大小排序(3456……A2大王) 通过索引也就是key键
TreeSet<Integer> wanjia1 = new TreeSet<>();//玩家1
TreeSet<Integer> wanjia2 = new TreeSet<>();//玩家2
TreeSet<Integer> wanjia3 = new TreeSet<>();//玩家3
TreeSet<Integer> dipai = new TreeSet<>();//三张底牌
//循环顺序发牌
for (int i = 0; i < list.size(); i++) {
if (i>=list.size()-3) {//最后剩余3张底牌
dipai.add(list.get(i));//将三张底牌存储到底牌集合中
}else if (i%3==0) {//三人求模得到第一张
wanjia1.add(list.get(i));
}else if (i%3==1) {//第二张
wanjia2.add(list.get(i));
}else {//第三张
wanjia3.add(list.get(i));
}
}
//4.玩家看牌 这里封装方法直接调用传入(所有牌,玩家发牌后的有序对象,玩家姓名自定义)
lookpoker(hmHashMap, wanjia1, "玩家1");
lookpoker(hmHashMap, wanjia2, "玩家2");
lookpoker(hmHashMap, wanjia3, "玩家3");
lookpoker(hmHashMap, dipai, "底牌");
//System.out.println(hmHashMap);
}
public static void lookpoker(HashMap<Integer, String> map,TreeSet<Integer> tSet,String wanjia) {
System.out.print(wanjia+"的牌是:");
for (Integer i : tSet) { //i代表双列集合中的每一个键
System.out.print(map.get(i)+" ");//遍历有序集合中的索引,从牌盒中取出对应的值。 例如:i=53 map.get(53)=大王
}
System.out.println();//换行
}
}
运行之后的效果: