Collctions集合所要用到方法
分析业务需求
- 总共有54张牌
- 点数: "3","4","5","6","7","8","9","10","J","Q","K","A","2“
- 花色: "♠", "♥", "♣", "♦“
- 大小王: "👲" , "🃏“
- 斗地主:发出51张牌,剩下3张做为底牌。
分析实现
- 在启动游戏房间的时候,应该提前准备好54张牌
- 接着,需要完成洗牌、发牌、对牌排序、看牌
// 测试类
public class Game {
public static void main(String[] args) {
Room m=new Room();
m.start();
}
}
//定义牌类
public class Card {
private String number;//牌的数字
private String color;//牌的花色
private int size;//牌的大小
public Card() {
}
public Card(String number, String color, int size) {
this.number = number;
this.color = color;
this.size = size;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
//重写toString方法,输出的是值而不是地址
@Override
public String toString() {
return color+number;
}
}
public class Room {
// 必须有一副牌
private List<Card> cardAll=new ArrayList<>();
int size=0;//表示每张牌的大小
public Room(){
// size++作用表示每张牌代表的大小
// 0 1 2 3 4 5 6 7 8 9 10 12 13
String[] numbers={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] colors={"♣","♠","♥","♦"};
//便利点数,在遍历花色,给每个点数赋上花色
//增强for循环
for (String number : numbers) {
size++;
for (String color : colors) {
Card card=new Card(number,color,size);
cardAll.add(card);//将牌存入集合中取
}
}
//单独存入大小王
Card c1=new Card("","🃏" ,++size);
Card c2=new Card("","🤡" ,++size);
Collections.addAll(cardAll,c1,c2);
System.out.println("按照顺序存入一副新牌:"+cardAll);
}
public void start() {
//Collections提供的shuffle方法 打乱集合中的顺序
Collections.shuffle(cardAll);
System.out.println("打乱顺序的牌:"+cardAll);
// 存入三个对象来接牌
List<Card> genie=new ArrayList<>();
List<Card> xiaozhuang=new ArrayList<>();
List<Card> hanfei=new ArrayList<>();
//发牌
//三个玩家一人一张顺序发牌,对3进行取余,第一个玩家余数为0 第二个玩家余1,第三个玩家余2
//[♥A, ♠8, ♣4, ♥10, 🃏, ♠J, ♠A, ♣3, ♦8, ♠10, ♠9, ♣8, ♦7, ♥9, ♥2, ♣5, ........
//玩家1 玩家2 玩家3 玩家1....... %3
//长度减3 是要留三张底牌
for (int i = 0; i < cardAll.size()-3; i++) {
Card c=cardAll.get(i);
if(i%3==0){
genie.add(c);//盖聂接牌
} else if (i%3==1) {
xiaozhuang.add(c);//小庄接牌
} else if (i%3==2) {
hanfei.add(c);//韩非接牌
}
}
//Collections集合提供sort方法进行排序
sortCard(genie);
sortCard(xiaozhuang);
sortCard(hanfei);
System.out.println("盖聂的牌:"+genie);
System.out.println("小庄的牌:"+xiaozhuang);
System.out.println("韩非的牌:"+hanfei);
//留3张底牌,subList截取集合从多少到多少(个人理解)
List<Card> lastThreeCards = cardAll.subList(cardAll.size() - 3, cardAll.size());
System.out.println(lastThreeCards);
genie.addAll(lastThreeCards);
sortCard(genie);
System.out.println("genie的牌:"+genie);
}
private void sortCard(List<Card> cards) {
Collections.sort(cards, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return o2.getSize()-o1.getSize();//对牌进行降序排序
//return o1.getSize()-o2.getSize();//升序排序
}
});
}
}
运行结果: