package cn.edu.lcudcc.collection_test; 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; } }
package cn.edu.lcudcc.collection_test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class GameDemo { public static List<Card> allCards = new ArrayList<>(); static { String[] sizes = {"3","4","5","6","7","8","9","10","J","Q","K","1","2"}; String[] colors = {"♠","♥","♣","♦"}; int index = 0; // 記錄牌的大小 for (String size : sizes) { index++ ; for (String color : colors) { Card c = new Card(size, color, index); 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) { Collections.shuffle(allCards); System.out.println("洗牌後:" + allCards); List<Card> zhangsan = new ArrayList<>(); List<Card> lisi = new ArrayList<>(); List<Card> wangwu = new ArrayList<>(); for (int i = 0; i < allCards.size() - 3; i++) { Card c = allCards.get(i); if(i%3==0) { zhangsan.add(c); } else if (i%3==1) { lisi.add(c); } else if(i%3==2){ wangwu.add(c); } } List<Card> lastThreeCards = allCards.subList(allCards.size()-3, allCards.size()); // 給玩家的牌排序(從大到小) sortCards(zhangsan); sortCards(lisi); sortCards(wangwu); System.out.println("小三:" + zhangsan); System.out.println("小四:" + lisi); System.out.println("小五:" + wangwu); 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 o1.getIndex() - o2.getIndex(); } }); } }