• 通过程序实现斗地主的过程,洗牌,发牌,看牌。要求对牌进行排序。


    public class Demo2 {
        public static void main(String[] args) {
            //创建HashMap集合,key是编号,value是扑克牌
            HashMap<Integer, String> hm = new HashMap<>();
            //创建ArrayList集合存储编号
            ArrayList<Integer> arr = new ArrayList<>();
            //创建花色数组
            String[] color = {"♥", "♠", "♦", "♣"};
            //创建数字数组
            String[] number = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "k", "A", "2",};
            int index = 0;//定义一个下标
            for (String num : number) {
                for (String col : color) {
                    //添加到HashMap集合中
                    hm.put(index, num + col);
                    //编号添加到ArrayList集合中
                    arr.add(index);
                    index++;
                }
            }
            hm.put(index, "大");
            arr.add(index);
            index++;
            hm.put(index, "小");
            arr.add(index);
    
            //此处也可以定义一个HashMap长度的随机数,取一个删除一个保证扑克不重复
            Collections.shuffle(arr);//洗牌,洗的是编号, Collections的shuffle()的方法实现的
    
            //发牌发的也是编号,保证编号有序,创建TreeSet集合   创建玩家和底牌
            TreeSet<Integer> player1 = new TreeSet<>();//玩家1
            TreeSet<Integer> player2 = new TreeSet<>();//玩家2
            TreeSet<Integer> player3 = new TreeSet<>();//玩家3
            TreeSet<Integer> poker = new TreeSet<>();//底牌
    
            //遍历把随机的编号添加到TreeSet集合中
            for (int i = 0; i < arr.size(); i++) {
                //
                Integer x = arr.get(i);
                if (i >= arr.size() - 3) {
                    poker.add(x);
                } else if (i % 3 == 0) {
                    player1.add(x);
                } else if (i % 3 == 1) {
                    player2.add(x);
                } else if (i % 3 == 2) {
                    player3.add(x);
                }
            }
    
            //调用方法
            lookpoker("张三", player1, hm);
            lookpoker("李四", player2, hm);
            lookpoker("王五", player3, hm);
            lookpoker("底牌", poker, hm);
    
        }
    
        /**
         * 遍历TreeSet集合,获取编号,到HashMap集合中找对应的牌
         * @param name 名字
         * @param ts    玩家
         * @param hm    扑克
         */
        public static void lookpoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) {
            System.out.println(name + "的牌是:");
            for (Integer t : ts) {
                //Object get(Object key): 获取指定key对应的value
                String pokers = hm.get(t);
                System.out.print(pokers + " ");
            }
            System.out.println();
        }
    
    }
    
  • 相关阅读:
    Git常用命令
    Shell脚本学习
    Shell脚本学习
    Shell脚本学习
    Git ignore文件的用法
    RSA非对称加密算法
    C++ 标准库中的堆(heap)
    EM(Entity FrameWork)- code first , using in Visual stdio 2017
    C# 图片文字识别
    C# 调 C++ DLL 托管代码中释放非托管函数分配的内存
  • 原文地址:https://www.cnblogs.com/zk2020/p/13977922.html
Copyright © 2020-2023  润新知