/*斗地主游戏
需求 : 在启动游戏房间的时候, 应该提前准备好54张牌,完成洗牌,发牌,牌顺序,逻辑
分析:
1. 当系统启动的同时需要准备好数据的时候, 就可以用静态代码块
2. 洗牌就是打乱牌的顺序
3. 定义三个玩家, 依次发出51张牌
4. 给玩家的牌进行排序(拓展)
5. 输出每个玩家的牌数据
*/
public class GameDemo {
/*
1.定义一个静态集合存储54张牌对象
*/
public static List<Card> allCards = new ArrayList<>();
/*
2. 做牌 : 定义静态代码块 初始化牌数据
*/
static {
//3.定义点数: 个数确定 ,类型确定, 使用数组
String[] size = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//4. 定义花色: 个数确定, 类型确定, 使用数组
String[] color = {"♠","♥","♦","♣"};
//5. 组合点数和花色
int i =1;
for (String s :size) {//(根据size依次对应花色匹配)
i++;
for (String c:color) {
//6.封装到一个牌集合
Card card = new Card(s,c,i);
allCards.add(card);//每遍历好一个 装入集合
}
}
//还有大小王另算
Card c1 = new Card("","🃏",++i);
Card c2 = new Card("","🤡",++i+1);
Collections.addAll(allCards,c1,c2);//利用Collections方法一起装如集合
}
public static void main(String[] args) {
//9.洗牌 利用Collections 方法
Collections.shuffle(allCards);
//10.发牌(定义三个玩家) 玩家实际作为集合容器
ArrayList<Card> linhuchong = new ArrayList<>();
ArrayList<Card> jiumozhi = new ArrayList<>();
ArrayList<Card> renyingying = new ArrayList<>();
//11.开始发牌(从牌集合中发出51张牌给三个玩家,剩三张作为底牌)
for (int i = 0; i < allCards.size() - 3; i++) {
//先拿到当前牌对象
Card c = allCards.get(i);
if (i % 3 ==0){
linhuchong.add(c);
}else if(i % 3 ==1){
jiumozhi.add(c);
}else if (i % 3 ==2){
renyingying.add(c);
}
}
//12. 拿到最后三张底牌() [51-3 , 54) 包前不包后
List<Card> lastThreeCards = allCards.subList(allCards.size() - 3, allCards.size());
//剩余三张牌
System.out.println(lastThreeCards);
//13.给玩家的牌排序(从小到大) (在Card里定义一个值来保存大小)
sortCards(linhuchong);
//14.输出玩家的牌:
System.out.println(linhuchong);
}
/*
给牌排序 方法
*/
public static void sortCards(List<Card> cards){
Collections.sort(cards, new Comparator<Card>() {
@Override
public int compare(Card o1, Card o2) {
return o2.getIndex()-o1.getIndex();
}
});
}
}
=====================================
牌类
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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端