Java用集合实现斗地主发牌

本文以java双列集合HashMap为核心实现发牌操作:                               

思路:

1.准备牌:创建一个Map集合,存储牌的索引和组装好的牌

     创建一个list集合,来储存牌的索引。

     定义一个花色数组和牌的点数大小的数组,双重for循环来组装牌,大小王单独存入集合

2.洗牌:Colletions中的shuffle(List)方法来打乱牌的顺序

3.发牌:定义4个集合,存储玩家牌的索引和底牌的索引, 遍历存储牌索引的List集合,获取每一个牌的索引

4.排序:使用Collections中的方法sort(List)默认是升序排序

5.看牌:定义一个lookpoker()方法

代码:

    public static void main(String[] args) {
        //存扑克
        HashMap<Integer, String> poker = new HashMap<>();
        //存扑克牌的索引
        ArrayList<Integer> pokerIndex = new ArrayList<>();
        //通过循环遍历组装牌;
        String[] colors = {"♠","♥","♣","♦"};
        String[] numbers = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
        int index = 0;
        poker.put(index, "大王");
        pokerIndex.add(index++);
        poker.put(index, "小王");
        pokerIndex.add(index++);
 //循环嵌套遍历两个数组,组装52张牌,存储到集合中
for (String number : numbers) { for (String color : colors) { poker.put(index, color + number); pokerIndex.add(index++); } } // System.out.println(poker);
      //打乱牌的顺序 Collections.shuffle(pokerIndex); // System.out.println(pokerIndex); ArrayList<Integer> play1 = new ArrayList(); ArrayList<Integer> play2 = new ArrayList(); ArrayList<Integer> play3 = new ArrayList(); ArrayList<Integer> dipai = new ArrayList(); for (int i = 0; i < pokerIndex.size(); i++) { if (i >= 51) { dipai.add(pokerIndex.get(i)); } else if (i % 3 == 0) { play1.add(pokerIndex.get(i)); } else if (i % 3 == 1) { play2.add(pokerIndex.get(i)); } else { play3.add(pokerIndex.get(i)); } }       
// 使用Collections中的方法sort(List)默认是升序排序
        Collections.sort(dipai);
        Collections.sort(play1);
        Collections.sort(play2);
        Collections.sort(play3);

        lookPoker("赌圣", poker, play1);
        lookPoker("赌侠", poker, play2);
        lookPoker("赌神", poker, play3);
        lookPoker("底牌", poker, dipai);
    }

    /*
        定义一个看牌的方法,提高代码的复用性
        参数:
            String name:玩家名称
            HashMap<Integer,String> poker:存储牌的poker集合
            ArrayList<Integer> list:存储玩家和底牌的List集合
        查表法:
             遍历玩家或者底牌集合,获取牌的索引
             使用牌的索引,去Map集合中,找到对应的牌
     */
    public static void lookPoker(String name, HashMap<Integer, String> poker, ArrayList<Integer> list) {
        //输出玩家名称,不换行
        System.out.print(name + ":");
        //遍历玩家或者底牌集合,获取牌的索引
            for (Integer key : list) {
            //使用牌的索引,去Map集合中,找到对应的牌
            String value = poker.get(key);
            System.out.print(value + " ");
        }
        System.out.println();//打印完每一个玩家的牌,换行
    }
原文地址:https://www.cnblogs.com/jiezai/p/11186143.html