Java代碼模擬鬥地主實現

package com.test;

import org.junit.Test;

import java.util.*;

/**
 * @program: study
 * @description: 模擬鬥地主
 * @author: Elias.Guo
 * @create: 2020-06-11 16:41
 **/
public class MoNiDouDiZhu {
    @Test
    public void test(){
        //創建HashMap key是編號,值是牌
        HashMap<Integer,String> map =new HashMap<>();
        //創建List,存儲編號
        List<Integer> list =new ArrayList<>();

        //創建花色數組
        String[] colors ={"♦", "♣", "♠", "♥"};
        //創建牌數組
        String[] numbers={"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};

        //遍歷,存儲牌和編號
        int index =0;
        for (String color : colors) {
            for (String number : numbers) {
                String poker =color+number;
                map.put(index,poker);
                list.add(index);
                index++;
            }
        }
        //添加大小王
        map.put(index,"大王");
        list.add(index);
        index++;
        map.put(index,"小王");
        list.add(index);

        //洗牌
        Collections.shuffle(list);

        //定義玩家
        TreeSet<Integer> faGe=new TreeSet<>();
        TreeSet<Integer> reBa=new TreeSet<>();
        TreeSet<Integer> me=new TreeSet<>();
        TreeSet<Integer> dePai=new TreeSet<>();

        //發牌
        for(int i=0;i<list.size();i++){
            if(i>=list.size()-3){
                //底牌
                dePai.add(list.get(i));
            }else if(i%3==0){
                //發哥
                faGe.add(list.get(i));
            }else if(i%3==1){
                //熱巴
                reBa.add(list.get(i));
            }else if(i%3==2){
                //華仔
                me.add(list.get(i));
            }
        }

        //看牌方法調用
        showPoker("發哥", faGe, map);
        showPoker("迪麗熱巴", reBa, map);
        showPoker("迪麗熱巴的老公(我)", me, map);
        showPoker("底牌",dePai,map);

    }
    public static void showPoker(String name, TreeSet<Integer> tr, HashMap<Integer, String> map) {
        System.out.print(name + "的牌是:");
        for (Integer key : tr) {
            String value = map.get(key);
            System.out.print(value + " ");
        }
        System.out.println();
        System.out.println("-------------------");
    }


}

輸出結果:

發哥的牌是:♦5 ♦J ♦A ♣7 ♣10 ♣J ♣K ♣2 ♠6 ♠10 ♠A ♠2 ♥6 ♥7 ♥8 ♥10 ♥K 
-------------------
迪麗熱巴的牌是:♦4 ♦9 ♣3 ♣6 ♣8 ♣Q ♣A ♠4 ♠5 ♠7 ♠J ♠K ♥3 ♥9 ♥Q ♥A 小王 
-------------------
迪麗熱巴的老公(我)的牌是:♦3 ♦6 ♦7 ♦8 ♦K ♦2 ♣4 ♣5 ♣9 ♠3 ♠8 ♠Q ♥4 ♥5 ♥J ♥2 大王 
-------------------
底牌的牌是:♦10 ♦Q ♠9 
-------------------

Process finished with exit code 0

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章