//在启动游戏房间是,应该提前准备好54张牌,完成洗牌,发牌,牌排序,逻辑。 功能: 1.做牌 2.洗牌 3.发牌 4.排序 5.看牌
//定义牌类
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;
}
}
//定义主类,实现功能
//在启动游戏房间是,应该提前准备好54张牌,完成洗牌,发牌,牌排序,逻辑。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Game {
/**
1.定义一个静态的集合存储54张牌对象
*/
public static List<Card> allCards = new ArrayList<>();
/**
2.做牌:定义静态代码块初始化牌数据 //在执行main方法时静态代码块优先执行
*/
static {
//3.定义点数:个数确定,类型确定,使用数组
String[] sizes = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//4.定义花色:个数确定,类型确定,使用数组
String[] colors = {"♣","♠","♥","♦"};
//5.组合点数和花色
int index = 0;//记录牌的大小
//用foreach循环遍历
for (String size : sizes) {
index++;
for (String color : colors) {
//6.封装成一个牌对象
Card c = new Card(size,color,index);
//7.存入到集合容器中去
allCards.add(c);
}
}
//8.大小王存入到集合中去
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) {
//9.洗牌 用Collections工具类的方法shuffle打乱排顺序
Collections.shuffle(allCards);
System.out.println("洗牌后:"+allCards);
//10.发牌(定义三个玩家,每个玩家的牌也是一个集合容器)
List<Card> wanjia1 = new ArrayList<>();
List<Card> wanjia2 = new ArrayList<>();
List<Card> wanjia3 = new ArrayList<>();
//11.开始发牌(从牌集合中发出51张牌给三个玩家,剩余3张牌作为底牌)
for (int i = 0; i < allCards.size()-3; i++) {
//先拿到当前牌对象
Card c = allCards.get(i);
//轮循环 一般用取余
if(i % 3 == 0){
//发给玩家1
wanjia1.add(c);
}else if(i % 3 == 1){
//发给玩家2
wanjia2.add(c);
}else if (i % 3 == 2){
//发给玩家3
wanjia3.add(c);
}
}
//12.拿到最后三张牌(把最后三张牌截取成一个子集和)
List<Card> lastThreeCards = allCards.subList(allCards.size()-3,allCards.size());//包前不包后
//13.给玩家的牌排序(从大到小)
sortCards(wanjia1);
sortCards(wanjia2);
sortCards(wanjia3);
//14.输出玩家的牌
System.out.println("玩家1:"+wanjia1);
System.out.println("玩家2:"+wanjia2);
System.out.println("玩家3:"+wanjia3);
System.out.println("三张底牌:"+lastThreeCards);
}
/**
* 给牌排序
* @param
*/
private static void sortCards(List<Card> cards) {
//cards = [7♣, Q♥, 🃏, 10♠, 8♦, K♦
Collections.sort(cards, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return o2.getIndex()-o1.getIndex();
}
});
}
}