Java Se模拟斗地主【练习使用集合】

模拟斗地主

目的:练习使用集合

思路:

  • 共54张牌分为四种花色,故可用循环得到52张牌
  • HashMap:用来保存所有的牌,其键为Integer类型,值为String类型
  • ArrayList:用来保存索引
  • TreeSet:用来保存玩家和底牌(可以进行自然排序,看起来整齐)
  • 洗牌:通过Collections中的shuffle方法(打乱集合)
  • 最后通过索引在map中查找玩家的牌
  1. 定义两个数组 分别存放花色和牌大小
  2. 创建HashMap集合用于存放所有的牌
  3. 创建ArrayList用来保存牌的索引
  4. 采用嵌套循环产生52张牌,并将牌和索引添加到Map集合,index添加到ArrayList集合
  5. 添加大王和小王 到此牌准备完成
  6. 通过Collections的shuffle方法打乱数组索引
  7. 创建四个TreeSet集合 分别表示三个玩家和底牌
  8. 开始发牌,通过普通for循环遍历arraylist集合,通过判断发牌
  9. 写看牌方法 即通过遍历treeset集合中的索引,通过索引去map中查找牌
    10.调用看牌方法

运行结果展示:
运行结果

package cn.dreamyi.demo1.doudizhu;

import java.util.*;

public class Doudizhu {
    
    
    public static void main(String[] args) {
    
    

        String[] colors = {
    
    "♦", "♥", "♣", "♠"};
        String[] numbers = {
    
    "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};

        //创建map集合保存所有牌
        HashMap<Integer, String> hm = new HashMap<>();
        ArrayList<Integer> al = new ArrayList<>();//保存牌的索引

        int index = 0;
        for (String color : colors) {
    
    
            for (String number : numbers) {
    
    
                al.add(index);
                hm.put(index, color + number);
                index++;
            }
        }
        hm.put(index, "小王");
        al.add(index);
        index++;
        hm.put(index, "大王");
        al.add(index);

        //洗牌 打乱顺序
        Collections.shuffle(al);

        //创建三个玩家和底牌集合
        TreeSet<Integer> play1 = new TreeSet<>();
        TreeSet<Integer> play2 = new TreeSet<>();
        TreeSet<Integer> play3 = new TreeSet<>();
        TreeSet<Integer> dp = new TreeSet<>();

        //开始发牌
        for (int i = 0; i < al.size(); i++) {
    
    
            if (i >= al.size() - 3) {
    
    
                dp.add(al.get(i));
            } else {
    
    
                if (i % 3 == 0) {
    
    
                    play1.add(al.get(i));
                } else if (i % 3 == 1) {
    
    
                    play2.add(al.get(i));
                } else if (i % 3 == 2) {
    
    
                    play3.add(al.get(i));
                }
            }
        }
        //看牌
        lookPoker("张三",play1,hm);
        lookPoker("李四",play2,hm);
        lookPoker("王五",play3,hm);
        lookPoker("底牌",dp,hm);
    }

    /**
     * 定义发看牌方法
     * @param play 玩家名字
     * @param list 玩家的索引
     * @param map 洗过后的牌
     */
    public static void lookPoker(String play,TreeSet<Integer> list,Map<Integer,String> map){
    
    
        System.out.println(play+"的牌:");
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        for(Integer i:list){
    
    
            System.out.print(map.get(i)+" ");
        }
        System.out.println();
    }
}

公众号:从简出发【mmk_xgg】
一起学习
关注一起学习呀

猜你喜欢

转载自blog.csdn.net/weixin_42143994/article/details/114028169