Java——利用集合类实现简单斗地主发牌

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

public class DouDiZhu {
    public static void main(String[] args) {
        //牌谱
        HashMap<Integer, String> pooker = new HashMap<>();
        //List:store number
        List<Integer> pookernumber = new ArrayList<>();
        //定义出13个点数的数组
        String[] numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
        //定义4个花色数组
        String[] colors = {"♠", "♥", "♣", "♦"};
        //
        int index = 2;
        for (String number : numbers) {
            for (String color : colors) {
                pooker.put(index, color + number);
                pookernumber.add(index);
                index++;
            }
        }
        //存储大王,和小王
        pooker.put(0, "大王");
        pookernumber.add(0);
        pooker.put(1, "小王");
        pookernumber.add(1);

        //打乱编号
        Collections.shuffle(pookernumber);
        //发牌:三个玩家和底牌
        List<Integer> player1 = new ArrayList<>();
        List<Integer> player2 = new ArrayList<>();
        List<Integer> player3 = new ArrayList<>();
        List<Integer> bottom = new ArrayList<>();
        for (int i = 0; i < pookernumber.size(); i++) {
            if(i<17){
                player1.add(pookernumber.get(i));
            }else if(i<17+17){
                player2.add(pookernumber.get(i));
            }else if(i<17+17+17){
                player3.add(pookernumber.get(i));
            }else {
                bottom.add(pookernumber.get(i));
            }
        }
        //player number sort
        Collections.sort(player1);
        Collections.sort(player2);
        Collections.sort(player3);
        //show
        look("player1",player1,pooker);
        look("player2",player2,pooker);
        look("player3",player3,pooker);
        look("bottom",bottom,pooker);
    }
    public static void look(String name,List<Integer> player,HashMap<Integer,String> pooker){
        //遍历ArrayList集合,获取元素,作为键,到集合Map中找值
        System.out.print(name+" ");
        for(Integer key : player){
            String value = pooker.get(key);
            System.out.print(value+" ");
        }
        System.out.println();
    }
}

多次运行测试一下:

player1 ♠2 ♥2 ♥A ♣A ♦A ♠Q ♣Q ♦Q ♥J ♣9 ♣8 ♥7 ♠6 ♠5 ♣5 ♠4 ♦3 
player2 大王 ♦2 ♠K ♦K ♠J ♣J ♦J ♦10 ♥9 ♦8 ♣6 ♦6 ♥4 ♣4 ♦4 ♠3 ♥3 
player3 小王 ♣2 ♠A ♥K ♣K ♥Q ♥10 ♠9 ♦9 ♠8 ♥8 ♣7 ♦7 ♥6 ♥5 ♦5 ♣3 
bottom ♣10 ♠7 ♠10 
player1 小王 ♠2 ♥2 ♣2 ♠A ♣K ♦Q ♥J ♥9 ♣9 ♦9 ♠8 ♣8 ♣7 ♠4 ♣3 ♦3 
player2 ♦2 ♥K ♦K ♠Q ♦J ♣10 ♦10 ♠9 ♥8 ♦8 ♥6 ♣6 ♦6 ♠5 ♥4 ♠3 ♥3 
player3 大王 ♥A ♣A ♦A ♠K ♥Q ♠J ♣J ♥10 ♠7 ♥7 ♦7 ♠6 ♥5 ♣5 ♣4 ♦4 
bottom ♠10 ♦5 ♣Q 
player1 ♥2 ♦2 ♥A ♦A ♠K ♣J ♦J ♠10 ♣10 ♠9 ♣8 ♦8 ♣7 ♣6 ♥4 ♣4 ♦4 
player2 大王 小王 ♠2 ♣K ♦K ♠Q ♣Q ♥10 ♥9 ♦9 ♥8 ♥7 ♠6 ♥6 ♣5 ♠3 ♣3 
player3 ♣2 ♠A ♣A ♥K ♥Q ♦Q ♠J ♥J ♦10 ♣9 ♠7 ♦7 ♦6 ♥5 ♠4 ♥3 ♦3 
bottom ♦5 ♠8 ♠5 

 

posted @ 2019-05-27 07:05  大梦谁觉  阅读(380)  评论(0编辑  收藏  举报