在启动游戏房间时,应提前准备好54张牌完成洗牌,发牌,牌顺序逻辑。
1.当系统启动的同时需要准备好数据的时候,就可以用静态代码块了。
2.洗牌就是打乱牌的顺序。
3.定义三个玩家、依次发出51张牌
4.给玩家的牌进行排序
代码实现:
Card类(卡牌类)
package collection.map.d4_collection_test;
/**
定义牌的类
*/
public class Card {
private String size;
private String color;
private int index;//真正的牌的大小
public void setIndex(int index) {
this.index = 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;
}
/**
* 重写toString,直接输出牌的大小与花色
* @return
*/
@Override
public String toString() {
return size+color;
}
}
GemeDemo类(实现类)
package collection.map.d4_collection_test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class GameDemo {
/**
1.定义一个静态集合对象,存放54张牌
*/
public static List allcards=new ArrayList<>();
/**
2.做牌,定义静态代码块初始化牌数据
*/
static {
//3.定义点数:个数确定,类型确定,使用数组
String[] sizes={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//4.定义花色:个数确定,类型确定,使用数组
String[] colors={"♥","♠","♦","♣"};
//5.组合点数和花色
int index=0;//记录牌的大小
for (String size : sizes) {
index++;
for (String color : colors) {
//6.封装为牌对象
Card c=new Card(size,color,index);
//7.添加到集合中
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) {
//9.洗牌
Collections.shuffle(allcards);
System.out.println("洗牌后:"+allcards);
//10.发牌(定义三个玩家,每个玩家的牌也是一个集合容器)
List zhangsan=new ArrayList<>();
List lisi=new ArrayList<>();
List wangwu=new ArrayList<>();
//11.开始发牌(从牌中发出51张牌给3个玩家,剩余三张作为底牌)
//allCards={4♣, 6♥, 8♦, 6♣, 9♠, Q♠,...]
//i 0 1 2
for (int i = 0; i < allcards.size()-3; i++) {
//接到第i张牌
Card c= allcards.get(i);
//轮循算法,3个一循环分别发给三个玩家
if (i%3==0) {
zhangsan.add(c);
}else if(i%3==1){
lisi.add(c);
}else if (i%3==2){
wangwu.add(c);
}
}
//12.拿到剩余三张牌(把他们截取到一个子集合)
List lastThreeCards=allcards.subList(allcards.size()-3,allcards.size());
//13.给玩家的牌排序(从大到小)
sortCards(zhangsan);
sortCards(lisi);
sortCards(wangwu);
//14.输出玩家的牌
System.out.println("张三:"+zhangsan);
System.out.println("李四:"+lisi);
System.out.println("王五:"+wangwu);
System.out.println("三张底牌:"+lastThreeCards);
}
/**
*定义一个方法,实现对牌的从大到小的排序
* @param cards
*/
private static void sortCards(List cards) {
Collections.sort(cards, new Comparator() {
@Override
public int compare(Card o1, Card o2) {
return o2.getIndex()-o1.getIndex();//降序
}
});
}
}
运行截图: