java基础 模拟斗地主发牌

模拟斗地主发牌

1.案例介绍

规则:

  1. 组装54张扑克牌
  2. 54张牌顺序打乱
  3. 三个玩家参与游戏,三人交替摸牌,每人17张牌,后三张留作底牌
  4. 查看三人各自手中的牌(按照牌的大小排序)、底牌

2. 分析

  1. 准备牌:
    完成数字与纸牌的映射关系:
    使用双列Map(HashMap)集合,完成一个数字与字符串纸牌的对应关系(相当于一个字典)。
  2. 洗牌:
    通过数字完成洗牌发牌
  3. 发牌: 将每个人以及底牌设计为ArrayList,将后3张牌直接存放于底牌,剩余牌通过对3取模依次发牌。
    存放的过程中要求数字大小与斗地主规则的大小对应。
    将代表不同纸牌的数字分配给不同的玩家与底牌。
  4. 看牌:
    通过Map集合找到对应字符展示。
    通过查询纸牌与数字的对应关系,由数字转成纸牌字符串再进行展示。

3.代码

public class Test7 {
    public static void main(String[] args) {
        //定义一个Map集合和List集合来存取牌号和索引
        Map<Integer, String> map = new HashMap();

        List<Integer> pokerindex = new ArrayList<>();

        //定义牌
        String[] num = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
        String[] color = {"♥", "♠", "♣", "♦"};

        //存牌号和与之对应的索引
        int index = 0;
        for (String s : num) {
            for (String c : color) {
                map.put(index, c + s);
                pokerindex.add(index);
                index++;
            }
        }
        //存大小王
        map.put(index, "大王");
        pokerindex.add(index);
        index++;
        map.put(index, "小王");
        pokerindex.add(index);

        //打乱牌组;
        Collections.shuffle(pokerindex);

        //创建四个集合
        List<Integer> dipai = new ArrayList<>();
        List<Integer> player1 = new ArrayList<>();
        List<Integer> player2 = new ArrayList<>();
        List<Integer> player3 = new ArrayList<>();
        //将打乱的索引数组分配给三个人
        for (int i = 0; i < pokerindex.size(); i++) {
            if (i > 50) {
                dipai.add(pokerindex.get(i));
            } else if (i % 3 == 0) {
                player1.add(pokerindex.get(i));
            } else if (i % 3 == 2) {
                player2.add(pokerindex.get(i));
            } else if (i % 3 == 1) {
                player3.add(pokerindex.get(i));
            }
        }
        //给每个人的牌组排序
        Collections.sort(player1);
        Collections.sort(player2);
        Collections.sort(player3);
        Collections.sort(dipai);
        //显示每个人的牌组
        show("张三", map, player1);
        show("李四", map, player2);
        show("王五", map, player3);
        show("底牌", map, dipai);


    }

    //定义一个方法用来显示牌组
    public static void show(String name, Map<Integer, String> map, List<Integer> player) {
        System.out.print(name);
        for (int i = 0; i < player.size(); i++) {
            Integer ii = player.get(i);
            System.out.print(map.get(ii) + " ");
        }
        System.out.println();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值