List集合以及工具类Collections
p136斗地主发牌逻辑
Card类
package com.itheima;
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 com.itheima;
import java.util.*;
public class Txet2 {
public static List<Card> allCards=new ArrayList<Card>();
static{
String[] size={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] color={"♠","♥","♣","◇"};
int index=0;
for (int i = 0; i < size.length; i++) {
index++;
for (int j = 0; j < color.length; j++) {
Card c=new Card(size[i],color[j],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> Ling=new ArrayList<Card>();
List<Card> Jiu=new ArrayList<Card>();
List<Card> Ren=new ArrayList<Card>();
for (int i = 0; i < allCards.size(); i++) {
Card c=allCards.get(i);
if(i%3==0){
Ling.add(c);
} else if (i%3==1) {
Jiu.add(c);
} else if (i%3==2) {
Ren.add(c);
}
}
List<Card> lastThreeCards=allCards.subList(allCards.size()-3,allCards.size());
sortCards(Ling);
sortCards(Jiu);
sortCards(Ren);
// 14、输出玩家的牌:
System.out.println("啊冲:" + Ling);
System.out.println("啊鸠:" + Jiu);
System.out.println("盈盈:" + Ren);
System.out.println("三张底牌:" + lastThreeCards);
}
public 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();
}
});
}
}