初学者项目:模拟斗地主洗牌发牌

版权声明:版权归 你的pizza到了 所有,未经允许不可转载 https://blog.csdn.net/qq_38353993/article/details/82561874

1、案例分析

1)、将一副牌封装进入Map集合中,键为0-53的Integer数据,值为字符串

2)、洗牌:将Map集合的键放在List中,在使用Collections.shuffle()进行洗牌

3)、发牌:发给三个人,就是三个List加一个底牌的List

4)、看牌:将三人的List和底牌List的值进行排序(从大到小)

2、图解

这里写图片描述

3、代码实现:

public static void main(String[] args) {
        //1)、封装牌
        String[] colors = {"♥","♠","♦","♣"};//花色
        String[] num = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};//数字
        Map<Integer,String> pokerMap = new HashMap<>();//存放代表大小的键,代表牌面的值
        int index = 0;//键
        pokerMap.put(index++,"大王");//后++,先存入index=0,在对index++,牌中最大牌为大王,放在键为0的位置
        pokerMap.put(index++,"小王");
        for (String n:num) {
            for (String c:colors) {//使用加强for循环对牌的花色和数字进行拼接
                pokerMap.put(index++,c+n);
            }
        }

        //2)洗牌:将Map集合的键放在List中,在使用Collections.shuffle()进行洗牌
        //要将键存在List中是因为在洗牌时要使用Conllections.shuffle()方法,排序使用sort()方法
        Set<Integer> key = pokerMap.keySet();
        ArrayList<Integer> list = new ArrayList<>();
        list.addAll(key);
        Collections.shuffle(list);//利用shuffle()方法将list中元素的顺序打乱

        //3)发牌:发给三个人,就是三个List加一个底牌的List
        ArrayList<Integer> user1 = new ArrayList<>();
        ArrayList<Integer> user2 = new ArrayList<>();
        ArrayList<Integer> user3 = new ArrayList<>();
        ArrayList<Integer> dipai = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            if (i>=list.size() - 3){
                dipai.add(list.get(i));
            }else {
                if (i % 3 == 0){
                    user1.add(list.get(i));
                }
                if (i % 3 == 1){
                    user2.add(list.get(i));
                }
                if (i % 3 == 2){
                    user3.add(list.get(i));
                }
            }
        }

        //看牌:将三人的List和底牌List的值进行排序(从大到小)
        Collections.sort(user1);
        Collections.sort(user2);
        Collections.sort(user3);
        Collections.sort(dipai);
        System.out.println("玩家1:"+ getPoker(user1,pokerMap));
        System.out.println("玩家2:"+ getPoker(user2,pokerMap));
        System.out.println("玩家3:"+ getPoker(user3,pokerMap));
        System.out.println("底牌:"+ getPoker(dipai,pokerMap));
    }

    private static ArrayList<String> getPoker(ArrayList<Integer> user, Map<Integer, String> pokerMap) {
        ArrayList<String> pokerList = new ArrayList<>();
        for (int i = 0; i < user.size(); i++) {
            pokerList.add(pokerMap.get(user.get(i)));
        }
        return pokerList;
    }

猜你喜欢

转载自blog.csdn.net/qq_38353993/article/details/82561874