模拟斗地主发牌并排序

题目

模拟斗地主发牌,并对其进行排序

分析

将牌盒定义为一个双链结合,为每个来建立一个索引;
然后为每个索引建立一个集合,洗牌和发牌都是使用索引;
将每个人各自的集合定义为 TreeSet 集合可以进行排序

程序代码

package com.company.test;


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

public class MyTest {
    public static void main(String[] args) {
        HashMap<Integer, String> pokerBox = new HashMap<>();
        //生成牌放进牌盒
        String[] nums = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
        String[] colors = {"♣", "♥", "♠", "♦"};
        int index = 0;
        //单独创建一个索引集合
        ArrayList<Integer> indexList = new ArrayList<>();
        for (String num : nums) {
            for (String color : colors) {
                pokerBox.put(index, num.concat(color));
                indexList.add(index);
                index++;

            }
        }
        //手动添加大小王
        pokerBox.put(index, "★");
        indexList.add(index);
        index++;
        pokerBox.put(index, "☆");
        indexList.add(index);
        //洗牌,洗索引集合
        Collections.shuffle(indexList);
        Collections.shuffle(indexList);
        Collections.shuffle(indexList);
        TreeSet<Integer> 刘备 = new TreeSet<>();
        TreeSet<Integer> 关羽 = new TreeSet<>();
        TreeSet<Integer> 张飞 = new TreeSet<>();
        TreeSet<Integer> 底牌 = new TreeSet<>();
        //遍历索引集合,发牌
        for (int i = 0; i < indexList.size(); i++) {
            if (i >= indexList.size() - 3) {
                底牌.add(indexList.get(i));
            } else if (i % 3 == 0) {
                刘备.add(indexList.get(i));
            } else if (i % 3 == 1) {
                关羽.add(indexList.get(i));
            } else {
                张飞.add(indexList.get(i));
            }
        }
        //看牌
        lookPoker("刘备", 刘备, pokerBox);
        lookPoker("关羽", 关羽, pokerBox);
        lookPoker("张飞", 张飞, pokerBox);
        lookPoker("底牌", 底牌, pokerBox);
    }

    private static void lookPoker(String name, TreeSet<Integer> set, HashMap<Integer, String> pokerBox) {
        System.out.println(name);
        for (Integer key : set) {
            String s = pokerBox.get(key);
            System.out.print(s + "  ");
        }
        System.out.println();
    }
}




运行结果

在这里插入图片描述

发布了68 篇原创文章 · 获赞 0 · 访问量 1167

猜你喜欢

转载自blog.csdn.net/weixin_45849948/article/details/105012383