代码演示如下:
Car类:
public class Card { private String size; private String color; private int index; public Card() { } public Card(String size, String color,int index) { this.size = size; this.color = color; this.index = index; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } @Override public String toString() { return size + color; } }
游戏测试类:
public class GameDemo { /** 1.定义一个静态的集合存储54张牌对象 */ public static List<Card> allCards = new ArrayList<>(); /** 2.做牌:定义静态代码块初始化数据 */ static{ //3.定义点数:个数确定,类型确定、使用数组 String[] sizes = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"}; //4.定义花色:个数确定,类型确定、使用数组 String[] colors = {"♠️","♥️","♣️","💠"}; //5.组合点数和花色 int index = 0; for (String size : sizes){ for (String color : colors){ //6.封装成一个牌对象 Card c = new Card(size,color,index); //7.存入到集合容器中去 allCards.add(c); } } Card c1 = new Card("","小🃏",++index); Card c2 = new Card("","大🃏",++index); Collections.addAll(allCards,c1,c2); System.out.println("新牌:" + allCards); } public static void main(String[] args) { //9.洗牌 Collections.shuffle(allCards); System.out.println("洗牌后:" + allCards); //10.发牌(定义三个玩家,每个玩家的牌也是一个集合容器) List<Card> 令狐冲 = new ArrayList<>(); List<Card> 鸠摩智 = new ArrayList<>(); List<Card> 任盈盈 = new ArrayList<>(); //11.开始发牌(从牌集合中发出51张牌给三个玩家,剩余3张做底牌) for (int i = 0; i < allCards.size(); i++) { Card c = allCards.get(i); if (i % 3 == 0){ 令狐冲.add(c); }else if (i % 3 == 1){ 鸠摩智.add(c); }else if (i % 3 == 2){ 任盈盈.add(c); } } //12.拿到最后三张底牌(把最后三张牌截取成一个子集合) List<Card> lastThreeCards = allCards.subList(allCards.size() - 3, allCards.size()); //13.给玩家的牌排序(从大到小) sortCards(令狐冲); sortCards(鸠摩智); sortCards(任盈盈); //14.输出玩家的牌: System.out.println("令狐冲:" + 令狐冲); System.out.println("鸠摩智:" + 鸠摩智); System.out.println("任盈盈:" + 任盈盈); System.out.println("三张底牌:" + lastThreeCards); } /** 给牌排序 * @param cards */ private static void sortCards(List<Card> cards) { Collections.sort(cards, new Comparator<Card>() { @Override public int compare(Card o1, Card o2) { return o2.getIndex() - o1.getIndex(); } }); } }