s-day04-双列集合实现斗地主案例

This commit is contained in:
2026-08-03 15:21:14 +08:00
parent 943af86cf2
commit 74668150e1
+91
View File
@@ -0,0 +1,91 @@
package com.inmind.test07;
import java.util.*;
/*
按照斗地主的规则,完成洗牌发牌的动作。
具体规则:
组装54张扑克牌将
54张牌顺序打乱
三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。
查看三人各自手中的牌(按照牌的大小排序)、底牌
要求:使用双列集合实现
<Integer,String>:键为牌的序号(排序),值为牌的名称
可以通过键找值的方式,来排序后看牌
*/
public class Test14 {
public static void main(String[] args) {
//创建一个双列集合,键为牌的序号,值为牌名称
HashMap<Integer,String> pokers = new HashMap<>();
//组装牌
String[] nums = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
String[] colors = {"", "", "","" };
//1~54 对应54张牌,54张打乱
ArrayList<Integer> keys = new ArrayList<>();
int key = 1;
for (String num : nums) {
for (String color : colors) {
pokers.put(key, color + num);
keys.add(key++);
}
}
//大小王
pokers.put(key, "小王");
keys.add(key++);
pokers.put(key, "大王");
keys.add(key);
System.out.println(pokers);
System.out.println(keys);
//洗牌
Collections.shuffle(keys);
System.out.println( keys);
//创建4个集合(3个玩家和1个底牌)
//创建一个降序的比较器给TreeSet使用
Comparator<Integer> comparator = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
TreeSet<Integer> player1 = new TreeSet<>(comparator);
TreeSet<Integer> player2 = new TreeSet<>(comparator);
TreeSet<Integer> player3 = new TreeSet<>(comparator);
TreeSet<Integer> dipai = new TreeSet<>(comparator);
/*
玩家1 0 3 6 %3 = 0
玩家2 1 4 7 %3 = 1
玩家3 2 5 8 %3 = 2
*/
for (int i = 0; i < keys.size(); i++) {
if (i >= 51) {
dipai.add(keys.get(i));
} else {
if (i % 3 == 0) {
player1.add(keys.get(i));
} else if (i % 3 == 1) {
player2.add(keys.get(i));
} else {
player3.add(keys.get(i));
}
}
}
//看牌
showPokers("玩家1", player1, pokers);
showPokers("玩家2", player2, pokers);
showPokers("玩家3", player3, pokers);
showPokers("底牌", dipai, pokers);
}
public static void showPokers(String name, TreeSet<Integer> pokerKeys, Map<Integer, String> pokers) {
String content = name + "";
//遍历键值,双列集合中,键找值
for (Integer pokerKey : pokerKeys) {
content += pokers.get(pokerKey) + " ";
}
System.out.println(content);
}
}