实现扑克的洗牌和发牌

import java.util.ArrayList;
import java.util.Collections;

/**
 * 问题:实现扑克的洗牌和发牌功能
 * 
 * 分析:
 *  初始化一副扑克的,创建集合对象将扑克放进去
 *    使用Collections的shuffle方法对集合进行洗牌
 *    实现发牌,发三家牌
 */
public class Exercise04 {


    public static void main(String[] args) {
        //将扑克数字和花色放到数组中
        String[] num = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        String[] color = {"红桃","黑桃","方片","梅花"};
        ArrayList<String> poker = new ArrayList<>();

        //拼接扑克的花色和数字放到ArrayList中
        for(String s1 : color) {
            for(String s2 : num) {
                poker.add(s1 + s2);
            }
        }
        poker.add("小王");
        poker.add("大王");
        //洗牌
        Collections.shuffle(poker);
        //发三家牌
        ArrayList<String> pony = new ArrayList<>();
        ArrayList<String> robin = new ArrayList<>();
        ArrayList<String> jack = new ArrayList<>();
        ArrayList<String> dipai = new ArrayList<>();

        for(int i = 0; i < poker.size(); i++) {
            if(i >= poker.size() - 3) {
                //留三张底牌
                dipai.add(poker.get(i));                    
            } else if(i % 3 == 0) {
                pony.add(poker.get(i));
            } else if(i % 3 == 1) {
                robin.add(poker.get(i));
            } else {
                jack.add(poker.get(i));
            }
        }

        //发牌
        System.out.println("pony:" + pony);
        System.out.println("robin:" + robin);
        System.out.println("jack:" + jack);
        System.out.println("dipai:" + dipai);
    }

}

实现扑克的洗牌和发牌

 -- 来源小猴子

 

其中有些算法还是可以学习和参阅的.

posted @ 2021-04-22 22:22  咸瑜  阅读(160)  评论(0编辑  收藏  举报