package com.inmind.map01; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; /* 案例介绍 按照斗地主的规则,完成洗牌发牌的动作。(洗牌打乱Collections.shuffle()只能打乱list集合) 具体规则: 组装54张扑克牌将54张牌顺序打乱 三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。(创建4个集合,3个玩家,1个底牌) 查看三人各自手中的牌(按照牌的大小排序)、底牌【自然排序或者比较器Comparable Comparator】 规则:手中扑克牌从大到小的摆放顺序:大王,小王,2,A,K,Q,J,10,9,8,7,6,5,4,3【打印牌即可】 54键----“大王” */ public class Test09 { public static void main(String[] args) { String[] nums = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; String[] colors = {"♦", "♣", "♥", "♠"}; //定义一个集合存放我们牌对象 ArrayList pokers = new ArrayList<>(); int index = 1; for (String num : nums) { for (String color : colors) { String pokerName = color+num; pokers.add(new Poker(pokerName,index++)); } } pokers.add(new Poker("小王", index++)); pokers.add(new Poker("大王", index++)); System.out.println(pokers); //洗牌 Collections.shuffle(pokers); System.out.println(pokers); //(创建4个集合,3个玩家,1个底牌) ArrayList play1 = new ArrayList<>(); ArrayList play2 = new ArrayList<>(); ArrayList play3 = new ArrayList<>(); ArrayList dipai = new ArrayList<>(); /* 玩家1 0 3 6 %3 = 0 玩家2 1 4 7 %3 = 1 玩家3 2 5 8 %3 = 2 */ for (int i = 0; i < pokers.size(); i++) { if (i > 50) { dipai.add(pokers.get(i)); } else { switch (i%3) { case 0: play1.add(pokers.get(i)); break; case 1: play2.add(pokers.get(i)); break; case 2: play3.add(pokers.get(i)); break; } } } //看牌之前先排序 //可以使用比较器替代自然排序 Comparator pokerComparator = new Comparator() { @Override public int compare(Poker o1, Poker o2) { return o2.index - o1.index; } }; Collections.sort(play1,pokerComparator); Collections.sort(play2,pokerComparator); Collections.sort(play3,pokerComparator); Collections.sort(dipai,pokerComparator); System.out.println("玩家1:"+play1); System.out.println("玩家2:"+play2); System.out.println("玩家3:"+play3); System.out.println("底牌:"+dipai); } }