分析:
-
准备牌阶段:创建一个存储54张扑克牌Map集合,在创建一个List集合,存储牌的索引(牌的大小),调用方法存储到集合中,在将54张牌利用增强for按“花色”+“大小”重新组合。
-
洗牌阶段:调用Collections.shuffle(poker)方法,将牌打乱,重组.
-
发牌阶段:利用数组的索引值进行循环判断,(0~53)%3,共用(0,1,2)三种结果,分别将得到不同结果的牌分给三位玩家,三个玩家每人17张牌索引大于等于51时,剩余牌为底牌。
-
准备工作: 调用 Collections.sort()方法,将牌进行升序排列。
-
看牌阶段:利用查表法,遍历集合数组,获得索引值为 key,在找对应的 value值分别进行输出。
一:代码实现:
public static void main(String[] args) {
// 准备牌,创建一个Map集合;
HashMap<Integer, String> poker = new HashMap<>();
// 创建一个ArrayList集合,存储牌的索引
ArrayList<Integer> pokerIndex = new ArrayList<>();
// 定义两个集合,一个数组存贮牌的花色,一个数组存储牌的序号;
List<String> colors = {
"♠", "♣", "♥", "♦"};
List<String> numbers = {
"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
// 添加大小王到集合中;
int index = 0;
poker.put(index, "大王");
pokerIndex.add(index);
index++;
poker.put(index, "小王");
pokerIndex.add(index);
index++;
// 循环嵌套遍历两个数组:组装52张牌;
for (String color : colors) {
for (String number : numbers) {
poker.put(index, color + number);
pokerIndex.add(index);
index++;
}
}
// 将牌的顺序进行打乱;
Collections.shuffle(poker);
// 发牌;创建4个集合,来存储牌;
ArrayList<Integer> player01 = new ArrayList<>();
ArrayList<Integer> player02 = new ArrayList<>();
ArrayList<Integer> player03 = new ArrayList<>();
ArrayList<Integer> dipai = new ArrayList<>();
for (int i = 0; i < pokerIndex.size(); i++) {
Integer in = pokerIndex.get(i);
if (i >= 51) {
// 用索引值来进行判断,
dipai.add(in);
} else if (i % 3 == 0) {
player01.add(in);
} else if (i % 3 == 1) {
player02.add(in);
} else if (i % 3 == 2) {
player03.add(in);
}
}
// 升序排列;
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(dipai);
// 看牌的方法,提高复用性;
lookpai("张三",poker,player01);
lookpai("李四",poker,player02);
lookpai("王五",poker,player03);
}
// 玩家名称;存储的HashMap类;存储的索引类;
// 查表法:
// 1 遍历玩家或者底牌集合,获取牌的索引;
// 2 使用牌的索引,去Map集合中,找对应的牌
public static void lookpai(String name, HashMap<Integer, String> poker,ArrayList<Integer> list) {
System.out.println(name + ": ");
for (Integer key : list) {
String value = poker.get(key);
System.out.println(value+" ");
}
System.out.println(); // 打印一个玩家后换行
}
二:运行结果:
张三: 大王 ♦A ♣K ♦K ♠Q ♦J ♣10 ♠10 ♥8 ♣8 ♦8 ♦6 ♠5 ♦5 ♥4 ♣3 ♦3
李四: ♠2 ♥A ♠K ♥K ♣Q ♦Q ♥J ♦10 ♥9 ♦9 ♠8 ♠7 ♣7 ♦7 ♣6 ♥5 ♠3
王五: 小王 ♦2 ♥2 ♣2 ♠A ♣A ♠J ♣J ♥10 ♠9 ♥7 ♠6 ♥6 ♠4 ♣4 ♦4 ♥3
底牌: ♥Q ♣9 ♣5
@喜欢的点赞关注,评论区留下宝贵的意见呐❥❥~