示例代码
创建牌类
index的作用:
一副牌有大小之分,而前面设置的点数和花样并不利于后面使用Collections来进行发给每个人的排序,所有再创建一个index来代表牌的大小值,并且是int类型的,才利于后面使用Collections.sort()方法排序
package com.zcl.d2_Demo;
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.zcl.d2_Demo;
import java.util.*;
// 目标:学会斗地主的洗牌
public class GameDemo {
public static List 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 c2 = new Card("","",++index);
Card c1 = 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 zhangs = new ArrayList<>();
List lisi = new ArrayList<>();
List wanwu = new ArrayList<>();
// 发牌:从allCards集合中发出51张牌给三个玩家,剩余3张作为底牌
// [7♥, 8♣, 9♣, 9♦, 5♣, K♣, 7♣, J♥, 10♠,
for (int i = 0; i < allCards.size() - 3; i++) {
// 拿到当前牌的对象
Card c = allCards.get(i);
// 对i取余判断发给谁
if(i % 3 == 0){
zhangs.add(c);
}else if(i % 3 == 1){
lisi.add(c);
}else if(i % 3 == 2){
wanwu.add(c);
}
}
// 拿到最后的三张牌,通过list的subList()方法截取
List lasThreeCards = allCards.subList(allCards.size()-3,allCards.size());
// 给玩家的牌进行排序(从大到小)
sortCards(zhangs);
sortCards(lisi);
sortCards(wanwu);
// 输出玩家的牌
System.out.println("张三的牌:"+zhangs);
System.out.println("李四的牌:"+lisi);
System.out.println("王武的牌:"+wanwu);
System.out.println("最好三张底牌:"+lasThreeCards);
}
private static void sortCards(List cards) {
// 简化之后的代码
Collections.sort(cards, (o1, o2)-> o1.getIndex() - o2.getIndex());
}
}
洗牌后的效果输出



