0
点赞
收藏
分享

微信扫一扫

java斗地主中级案例(利用了HashMap 集合的key不可重复,而value不可重复的特点)

天悦哥 2022-03-13 阅读 26
package cn.itcase.day27.demo01.demo02.demo03;

import java.util.*;

//最后每个人的牌是按顺序拍好的(任务)
/*Java斗地主升级版
* 1、利用HashMap来存储牌,打乱是打乱的是键,到时候获取键所对应的value值即可
* 2、Collections 中的shuffle()方法来进行打乱
* 3、用sort进行排序 */
public class Doudizhu {
    public static void main(String[] args) {
        HashMap<Integer,String> poker = new HashMap<>();
        ArrayList<Integer> pokerindex = new ArrayList<>();

        List<String> colors = List.of("♠","♥","♣","♦");
        List<String> pokers = List.of("2","A","k","Q","J","10","9","8","7","6","5","4","3");
        Integer index = 0;
        poker.put(index,"大王");
        pokerindex.add(index);
        index++;
        poker.put(index,"小王");
        pokerindex.add(index);
        index++;
        for(String poke : pokers){//这里嵌套循环不可倒换,若倒换则是按照花色来存储;
            for (String color : colors){
                poker.put(index,color+poke);
                pokerindex.add(index);
                index++;
            }
        }
        Collections.shuffle(pokerindex);
        ArrayList<Integer> play0 = new ArrayList<>();
        ArrayList<Integer> play1 = new ArrayList<>();
        ArrayList<Integer> play2 = new ArrayList<>();
        ArrayList<Integer> dipai = new ArrayList<>();
        for (int i = 0; i < pokerindex.size(); i++) {
            Integer in = pokerindex.get(i);
            if(i >= 51){
                dipai.add(in);
            }else if(i % 3 == 0){
                play0.add(in);
            }else if(i % 3 == 1){
                play1.add(in);
            }else if(i % 3 == 2){
                play2.add(in);
            }
        }
        Collections.sort(play0);
        Collections.sort(play1);
        Collections.sort(play2);

       /* System.out.println(pokerindex);
        System.out.println(poker);*/
       demo01("周润发",poker,play0);
       demo01("刘德华",poker,play1);
       demo01("周星驰",poker,play2);
    }

    private static void demo01(String name,HashMap<Integer,String> poker,ArrayList<Integer> list) {
        System.out.print(name +": ");
        for(Integer key : list){
            String value = poker.get(key);
            System.out.print(value+" ");
        }
        System.out.println();
    }
}

举报

相关推荐

0 条评论