解题思路
代码如图
public class workpuke {
/*
* 1. 组合54张牌
* 2. 洗牌
* 3. 三个玩家+底牌的发牌
* 4. 看牌
*/
@Test
public void test1(){
// 1.设置牌的4个花色
String[] flower = {"♥","♠","♦","♣"};
//2.准备牌
String[] puke = {"2","A","K","Q","J","10","9","8","7","6"
,"5","4","3"};
//3.创建一个Map集合,用于装54张牌和牌
int count = 2;
HashMap<Integer,String> hashMap = new HashMap<>();
//4.将花色和牌依次放入
//创建一个List集合,用于存放所有牌的牌号,为了后面洗牌和发牌
ArrayList<Integer> list = new ArrayList<>();
for (String flow: flower){
for (int i = 0; i < puke.length; i++) {
//4.将准备好的带有花色的牌放置到map集合中,还有对应的牌号
String pai = flow + puke[i];
hashMap.put(count, pai);
list.add(count);
count++;
}
}
System.out.println(hashMap);
hashMap.put(0, "大王");
list.add(0);
hashMap.put(1, "小王");
list.add(1);
//5.洗牌,将list中的所有牌号打乱
Collections.shuffle(list);
//6.创建三个玩家牌的容器,以及底牌容器
ArrayList<Integer> play1 = new ArrayList<>();
ArrayList<Integer> play2 = new ArrayList<>();
ArrayList<Integer> play3 = new ArrayList<>();
ArrayList<Integer> bottom = new ArrayList<>();
// 7. 发牌,三个玩家,每人17张,底牌3张
// 实际上发给玩家的是list集合中的牌号,循环发牌
// 前3张发给底牌
for (int i = 0; i <list.size(); i++) {
if (i<3){ //留做底牌
bottom.add(list.get(i));
}else {//剩下的所有牌发给3个玩家
if (i % 3 == 0){ //发给玩家1
play1.add(list.get(i));
}else if (i % 3 == 1){
play2.add(list.get(i));
}else if (i % 3 == 2){
play3.add(list.get(i));
}
}
}
//8.
// 8. 看牌
lookPai(play1,hashMap,"玩家1");
lookPai(play2,hashMap,"玩家2");
lookPai(play3,hashMap,"玩家3");
lookPai(bottom,hashMap,"底牌");
}
//8.看牌方法封装
public static void lookPai(ArrayList<Integer> play, Map<Integer,String> map,String name){
//1.先将玩家手中的牌号进行升序排列,对应的牌从大到小
Collections.sort(play );
//2.通过牌号到map集合中获取到真实的value值,就是真实牌
System.out.print(name+":");
for (Integer key: play){
String value= map.get(key);
System.out.print(value + "");
}
System.out.println();
}
}