牌属性类:
package Java_project_1;
import java.util.Objects;
public class Card {
private String size;//点数
private String color;//花色
private int index;//牌的真正大小
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;
}
@Override
public String toString() {
return size+ color ;
}
@Override
public int hashCode() {
return Objects.hash(size, color);
}
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 Card() {
}
}
游戏运行主体类:
package Java_project_1;
import java.util.*;
public class GameDemo {
public static List<Card> 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("","\uD83C\uDCCF",++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> linghuchong =new ArrayList<>();//第一位
List<Card> jiumozhi =new ArrayList<>();//第二位
List<Card> renyingying =new ArrayList<>();//第三位
//分牌
for (int i=0;i<allCards.size()-3;++i){
Card c =allCards.get(i);
if(i%3==0){
linghuchong.add(c);
} else if (i%3==1) {
jiumozhi.add(c);
} else if(i%3==2) {
renyingying.add(c);
}
}
List<Card>lastThreeCards=allCards.subList(allCards.size()-3,allCards.size());//截取最后3张底牌
//洗牌
shortCard(linghuchong);
shortCard(jiumozhi);
shortCard(renyingying);
//输出玩家的牌
System.out.println("啊冲" + linghuchong);
System.out.println("阿九" + jiumozhi);
System.out.println("盈盈" + renyingying);
System.out.println("三张底牌" + lastThreeCards);
}
/**
* 牌排序
* @param linghuchong
*/
private static void shortCard(List<Card> cards) {
Collections.sort(cards, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return o2.getIndex()- o1.getIndex();//降序
}
});
}
}