模拟斗地主洗牌发牌案例

package com.itheima.模拟斗地主.斗地主版本2;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;

public class Card {
    private HashMap hm;
    private ArrayList> list;

    public ArrayList> getList() {
        return list;
    }

    public Card() {
        //将54张牌按大小顺序放入Map集合中
        hm = new HashMap<>();
        String[] huase = {"♠", "♥", "♣", "♦"};
        String[] dianshu = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
        //定义一个变量,使得牌可以从0索引开始添加进去
        int count = 0;
        for (int i = 0; i < dianshu.length; i++) {
            for (int j = 0; j < huase.length; j++) {
                hm.put(count++, huase[j] + dianshu[i]);
            }
        }
        hm.put(count++, "小王");
        hm.put(count++, "大王");
    }

    public void xiCard(String name1, String name2, String name3) {
        //定义一个集合,依次赋值为0,1,2,3,4....
        ArrayList list1 = new ArrayList<>();
        for (int i = 0; i < 54; i++) {
            list1.add(i);
        }
        //重新排列
        Collections.shuffle(list1);
        //将打乱的值按一定规则赋予TreeSet集合
        TreeSet treeSet1 = new TreeSet<>();
        TreeSet treeSet2 = new TreeSet<>();
        TreeSet treeSet3 = new TreeSet<>();
        TreeSet dipai = new TreeSet<>();
        for (int i = 0; i < list1.size(); i++) {
            if (i >= list1.size() - 3) {
                dipai.add(list1.get(i));
            } else if (i % 3 == 0) {
                treeSet1.add(list1.get(i));
            } else if (i % 3 == 1) {
                treeSet2.add(list1.get(i));
            } else if (i % 3 == 2) {
                treeSet3.add(list1.get(i));
            }
        }
        list = new ArrayList<>();
        list.add(treeSet1);
        list.add(treeSet2);
        list.add(treeSet3);
        list.add(dipai);
        lookPoke("张三", treeSet1);
        lookPoke("李四", treeSet2);
        lookPoke("王五", treeSet3);
    }

    public void lookPoke(String name, TreeSet treeSet) {
        //按TreeSet里面的值去找HashMap里面的索引
        if (name.equals("底牌")) {
            System.out.print(name + "为:");
        } else {
            System.out.print(name + "的牌为:");
        }
        for (Integer i : treeSet) {
            System.out.print(hm.get(i) + " ");
        }
        System.out.println();
    }
}
package com.itheima.模拟斗地主.斗地主版本2;

import java.util.TreeSet;

public class Test {
    public static void main(String[] args) {
        Card card=new Card();
        //创建玩斗地主的玩家
        String[] str={"张三","李四","王五"};
        //洗牌发牌
        card.xiCard(str[0],str[1],str[2]);
        //看底牌
        card.lookPoke("底牌",card.getList().get(3));
        System.out.println("随机产生地主中...");
        //三个玩家中随机产生一个
        int i=(int)(Math.random()*3);
        //将底牌添加到地主牌中
        TreeSet ts= card.getList().get(i);
        ts.addAll(card.getList().get(3));
        //重新输出地主牌
        card.lookPoke("地主"+str[i],ts);
    }

}

测试效果:

模拟斗地主洗牌发牌案例_第1张图片

你可能感兴趣的:(JavaSE)