4

Java中的集合实现赌神、赌圣、赌侠斗地主

 1 year ago
source link: https://blog.51cto.com/zhanjq/5882526
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Java中的集合实现赌神、赌圣、赌侠斗地主

精选 原创

共饮一杯无 2022-11-24 09:17:28 博主文章分类:Java基础 ©著作权

文章标签 java 数组 泛型 文章分类 Java 编程语言 yyds干货盘点 阅读数169

代码如下:

//定义一个存储54张牌的ArrayList集合,泛型使用String
ArrayList<String> poker = new ArrayList<>();
//定义两个数组,一个数组存储牌的花色,一个数组存储牌的序号
String[] colors = {"♠","♥","♣","♦"};
String[] numbers = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
//先把大王和小王存储到poker集合中
poker.add("大王");
poker.add("小王");
//循环嵌套遍历两个数组,组装52张牌
for(String number : numbers){
    for (String color : colors) {
        //System.out.println(color+number);
        //把组装好的牌存储到poker集合中
        poker.add(color+number);
    }
}
/**
洗牌
使用集合的工具类Collections中的方法
static void shuffle(List<?> list) 使用默认随机源对指定列表进行置换。
*/
Collections.shuffle(poker);
//定义4个集合,存储玩家的牌和底牌
ArrayList<String> player01 = new ArrayList<>();
ArrayList<String> player02 = new ArrayList<>();
ArrayList<String> player03 = new ArrayList<>();
ArrayList<String> diPai = new ArrayList<>();

/**
    遍历poker集合,获取每一张牌
    使用poker集合的索引%3给3个玩家轮流发牌
    剩余3张牌给底牌
    注意:
        先判断底牌(i>=51),否则牌就发没了
 */
for (int i = 0; i < poker.size() ; i++) {
    //获取每一张牌
    String p = poker.get(i);
    //轮流发牌
    if(i>=51){
        //给底牌发牌
        diPai.add(p);
    }else if(i%3==0){
        //给玩家1发牌
        player01.add(p);
    }else if(i%3==1){
        //给玩家2发牌
        player02.add(p);
    }else if(i%3==2){
        //给玩家3发牌
        player03.add(p);
    }
}
//看牌
System.out.println("赌侠-刘德华:"+player01);
System.out.println("赌神-周润发:"+player02);
System.out.println("赌圣-周星驰:"+player03);
System.out.println("底牌:"+diPai);

最后输出如下:

赌侠-刘德华:[♠K, ♣3, ♠J, ♥J, ♠7, ♦4, ♣4, ♣Q, ♣2, ♣8, ♠9, ♣5, ♦A, ♣6, ♣A, ♦9, 小王]
赌神-周润发:[♥2, ♥8, ♠10, ♣J, ♣7, ♦8, ♦2, ♥6, ♥4, ♣10, ♠4, ♠5, ♠3, ♦6, ♥7, ♦3, ♦J]
赌圣-周星驰:[♥3, ♠6, ♦K, ♠8, ♥K, ♦10, ♥10, ♠Q, ♥9, ♠A, ♥5, ♥Q, 大王, ♦Q, ♥A, ♣9, ♦7]
底牌:[♣K, ♦5, ♠2]

本文内容到此结束了,
如有收获欢迎点赞👍收藏💖关注✔️,您的鼓励是我最大的动力。
如有错误❌疑问💬欢迎各位大佬指出。
主页 共饮一杯无的博客汇总👨‍💻

保持热爱,奔赴下一场山海。🏃🏃🏃

  • 1
  • 1收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK