定义牌类
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 int getIndex() {
return index;
}
public void setIndex(int index) {
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;
}
@Override
public String toString() {
return size + color;
}
}
主函数
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CardsGame {
public static List allCards = new ArrayList<>();
static {
String[] sizes = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "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);
}
public static void main(String[] args) {
System.out.println(allCards);
// 3、洗牌
Collections.shuffle(allCards);
System.out.println("洗牌后 " + allCards);
// 4、发牌(定义三个玩家,每个玩家也是一个集合容器)
List lyl = new ArrayList<>();
List lmy = new ArrayList<>();
List xxx = new ArrayList<>();
for (int i = 0; i < allCards.size() - 3; i++) {
Card c = allCards.get(i);
if(i % 3 == 0) {
lyl.add(c);
} else if (i % 3 == 1) {
lmy.add(c);
} else {
xxx.add(c);
}
}
//5、拿到最后三张牌
List lastThreeCards = allCards.subList(allCards.size() - 3, allCards.size());
// 6、给玩家的牌从大到小排序
sortCards(lyl);
sortCards(lmy);
sortCards(xxx);
// 输出每个人的牌
System.out.println("lyl " + lyl);
System.out.println("lmy " + lmy);
System.out.println("xxx " + xxx);
System.out.println("最后三张 " + lastThreeCards);
}
private static void sortCards(List cards) {
Collections.sort(cards, (Card o1, Card o2) -> {
return o2.getIndex() - o1.getIndex();
}
);
}
}