Tag Archives: HashMap

斗地主发牌的简单实现

ArrayList版

package com.yusian.poker;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class PokerDemo {
    public static void main(String[] args) {
        String[] colors = {"♠️", "♥️", "♣️", "♦️"};
        String[] numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
        ArrayList<String> poker = new ArrayList<>();
        poker.add("大王");
        poker.add("小王");
        for (String color : colors) {
            for (String number : numbers) {
                poker.add(number + color);
            }
        }
        System.out.println(poker);
        // 打乱顺序
        Collections.shuffle(poker);
        System.out.println(poker);
        ArrayList<String> player1 = new ArrayList<>();
        ArrayList<String> player2 = new ArrayList<>();
        ArrayList<String> player3 = new ArrayList<>();
        ArrayList<String> remain = new ArrayList<>();
        for (int i = 0; i < poker.size(); i++) {
            String p = poker.get(i);
            if (i >= 51) {
                remain.add(p);
            } else if (i % 3 == 0) {
                player1.add(p);
            } else if (i % 3 == 1) {
                player2.add(p);
            } else {
                player3.add(p);
            }
        }
        // 排序
        player1.sort(Comparator.comparingInt((String o) -> o.charAt(0)));
        player2.sort(Comparator.comparingInt((String o) -> o.charAt(0)));
        player3.sort(Comparator.comparingInt((String o) -> o.charAt(0)));
        System.out.println("------------------");
        System.out.println("player1:" + player1);
        System.out.println("player2:" + player2);
        System.out.println("player3:" + player3);
        System.out.println("底牌:" + remain);
    }
}
[大王, 小王, 2♠️, A♠️, K♠️, Q♠️, J♠️, 10♠️, 9♠️, 8♠️, 7♠️, 6♠️, 5♠️, 4♠️, 3♠️, 2♥️, A♥️, K♥️, Q♥️, J♥️, 10♥️, 9♥️, 8♥️, 7♥️, 6♥️, 5♥️, 4♥️, 3♥️, 2♣️, A♣️, K♣️, Q♣️, J♣️, 10♣️, 9♣️, 8♣️, 7♣️, 6♣️, 5♣️, 4♣️, 3♣️, 2♦️, A♦️, K♦️, Q♦️, J♦️, 10♦️, 9♦️, 8♦️, 7♦️, 6♦️, 5♦️, 4♦️, 3♦️]
[2♠️, J♣️, 4♦️, 5♠️, 9♠️, Q♠️, 6♠️, 7♠️, Q♦️, 3♦️, 2♣️, 4♣️, 10♦️, 9♦️, 3♥️, 7♦️, A♥️, 3♠️, 5♥️, K♥️, 9♥️, 8♠️, K♦️, A♦️, 5♣️, J♥️, K♠️, 2♦️, 6♣️, A♣️, 8♦️, 6♥️, 9♣️, 4♠️, 10♥️, 10♣️, 8♥️, 大王, J♠️, 5♦️, A♠️, Q♥️, 6♦️, 4♥️, 8♣️, 3♣️, K♣️, 2♥️, Q♣️, 7♥️, 10♠️, 7♣️, J♦️, 小王]
------------------
player1:[10♦️, 2♠️, 2♦️, 3♦️, 3♣️, 4♠️, 5♠️, 5♥️, 5♣️, 5♦️, 6♠️, 6♦️, 7♦️, 8♠️, 8♦️, 8♥️, Q♣️]
player2:[10♥️, 2♣️, 4♥️, 6♣️, 6♥️, 7♠️, 7♥️, 9♠️, 9♦️, A♥️, A♠️, J♣️, J♥️, K♥️, K♦️, K♣️, 大王]
player3:[10♣️, 10♠️, 2♥️, 3♥️, 3♠️, 4♦️, 4♣️, 8♣️, 9♥️, 9♣️, A♦️, A♣️, J♠️, K♠️, Q♠️, Q♦️, Q♥️]
底牌:[7♣️, J♦️, 小王]

HashMap版
[……]

继续阅读