public class Demo01 {
public static void main(String[] args) {
// 创建双列集合, 键值数字, 值为牌 (两个都是从小到大)
HashMap<Integer, String> map = new HashMap<>();
// 创建单列集合, 单列集合中的元素 就是map中的键
ArrayList<Integer> list = new ArrayList<>();
// 创建花色数组
String[] colors = {"♦", "♣", "♥", "♠"};
// 创建点数数组
String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
// 创建变量, 当做map集合的键
int index = 1;
// 先遍历点数数组
for (String number : numbers) {
// 在遍历花色数组
for (String color : colors) {
// 牌
String poker = color + number;
// 存到集合中
map.put(index, poker);
list.add(index++);
}
}
map.put(index, "♙");
list.add(index++);
map.put(index, "♛");;
list.add(index);
// 洗牌
Collections.shuffle(list);
// 发牌
// 创建3个人和1个底牌
ArrayList<Integer> me = new ArrayList<>();
ArrayList<Integer> gaoJin = new ArrayList<>();
ArrayList<Integer> longWu = new ArrayList<>();
ArrayList<Integer> left = new ArrayList<>();
// 遍历List集合
for (int i = 0; i < list.size(); i++) {
// 最后3张牌
if (i >= list.size() - 3) {
// 添加i索引对应的元素
left.add(list.get(i));
}else if (i % 3 == 0) {
me.add(list.get(i));
}else if (i % 3 == 1) {
gaoJin.add(list.get(i));
}else {
longWu.add(list.get(i));
}
}
// 排序
Collections.sort(me);
Collections.sort(gaoJin);
Collections.sort(longWu);
Collections.sort(left);
// 看牌
show(map, me, "我");
show(map, gaoJin, "高进");
show(map, longWu, "龙五");
show(map, left, "底牌");
}
/**
* 此方法用来看牌
*/
public static void show(HashMap<Integer, String> map, ArrayList<Integer> list , String name) {
// 字符串的拼接
StringBuilder sb = new StringBuilder(name);
sb.append(": ");
for (Integer key : list) {
String poker = map.get(key);
sb.append(poker).append(" ");
}
System.out.println(sb);
}
}
Java基础之"斗地主"
最新推荐文章于 2022-05-16 10:18:59 发布