【java学习笔记】模拟斗地主功能

时间:2022-08-28 00:16:34

模拟斗地主的功能:1.组合牌 2.洗牌 3.发牌 4.看牌,目的是温习回顾一下java集合框架的应用。

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Poker {
    public static void main(String[] args) {
        /*
         * 1.组合牌 创建Map集合,key是编号,value是牌
         */
        HashMap<Integer, String> poker = new HashMap<Integer, String>();
        /* 创建List集合存储编号 */
        ArrayList<Integer> pokerNumber = new ArrayList<Integer>();
        /* 定义13个点数的数组 */
        String[] figures = { "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3" };
        /* 定义4个花色的数组 */
        String[] colors = { "♥", "♠", "♦", "♣" };
        /* 定义整数变量,作为key */
        int index = 2;
        /* 遍历数组,将花色和点数的组合存储到Map集合中 */
        for (String figure : figures) {
            for (String color : colors) {
                poker.put(index, figure + color);
                pokerNumber.add(index);
                index++;
            }
        }
        /* 存储大小王 */
        poker.put(0, "大王");
        pokerNumber.add(0);
        poker.put(1, "小王");
        pokerNumber.add(1);
        /* 洗牌:将牌的序号打乱 */
        Collections.shuffle(pokerNumber);
        /* 发牌:将牌编号,发给玩家集合,底牌集合 */
        ArrayList<Integer> playerA = new ArrayList<Integer>();
        ArrayList<Integer> playerB = new ArrayList<Integer>();
        ArrayList<Integer> playerC = new ArrayList<Integer>();
        ArrayList<Integer> bottom = new ArrayList<Integer>();
        /* 发牌:集合索引%3 */
        for (int i = 0; i < pokerNumber.size(); i++) {
            /* 先存底牌 */
            if (i < 3) {
                bottom.add(pokerNumber.get(i));
            } else if (i % 3 == 0) {
                /* 发给玩家A */
                playerA.add(pokerNumber.get(i));
            } else if (i % 3 == 1) {
                /* 发给玩家B */
                playerB.add(pokerNumber.get(i));
            } else if (i % 3 == 2) {
                /* 发给玩家C */
                playerC.add(pokerNumber.get(i));
            }
        }
        /* 对玩家集合的编号进行排序 */
        Collections.sort(playerA);
        Collections.sort(playerB);
        Collections.sort(playerC);
        /* 看牌 */
        look("小莉", playerA, poker);
        look("小涵", playerB, poker);
        look("小琳", playerC, poker);
        look("底牌", bottom, poker);
    }

    /**
     * 看牌:将玩家集合中的编号作为key,去poker集合中查找value
     */
    public static void look(String name, ArrayList<Integer> player, HashMap<Integer, String> poker) {
        /* 遍历ArrayList集合,获取值作为key,到集合Map中查找Value */
        System.out.print(name + ":");
        for (Integer key : player) {
            String value = poker.get(key);
            System.out.print(value + " ");
        }
        System.out.println();
    }

}