import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.TreeSet;public class ddzDemo2 { /** * 斗地主--最终版 * * @param args * 定义牌 装牌 洗牌 发牌 看牌 */ public static void main(String[] args) { // 按从小到大存放牌 HashMaphmcard = new HashMap (); // 定义牌的序号 ArrayList indexcard = new ArrayList (); String[] colorCard = { "♣", "♦", "♥", "♠" }; String[] digitCard = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2" }; // 装牌 int index = 0; for (String d : digitCard) { for (String c : colorCard) { hmcard.put(index, c.concat(d)); indexcard.add(index); index++; } } hmcard.put(index, "小王"); indexcard.add(index); index++; hmcard.put(index, "大王"); indexcard.add(index); // 洗牌 Collections.shuffle(indexcard); // 发牌 TressSet有序 TreeSet player1 = new TreeSet (); TreeSet player2 = new TreeSet (); TreeSet player3 = new TreeSet (); TreeSet hole = new TreeSet (); for (int i = 0; i < indexcard.size(); i++) { if (i > indexcard.size() - 3 - 1) { hole.add(indexcard.get(i)); } else if (i % 3 == 0) { player1.add(indexcard.get(i)); } else if (i % 3 == 1) { player2.add(indexcard.get(i)); } else if (i % 3 == 2) { player3.add(indexcard.get(i)); } } // 看牌 checkcard("农民1", player1, hmcard); checkcard("农民2", player2, hmcard); checkcard("地主", player3, hmcard); checkcard("hole", hole, hmcard); } public static void checkcard(String name, TreeSet pl, HashMap hmcd) { StringBuilder sb = new StringBuilder(); for (int p : pl) { sb.append(hmcd.get(p) + " "); } if (name.equals("hole")) { System.out.println("底牌是: " + sb); } else { System.out.println(name + "的牌是: " + sb); } }}
运行:
农民1的牌是: ♣3 ♠3 ♣4 ♥4 ♠4 ♥8 ♠8 ♦9 ♠9 ♠10 ♦J ♥J ♣Q ♣K ♦A ♠A ♣2 农民2的牌是: ♥3 ♣5 ♥5 ♥6 ♠6 ♦7 ♣8 ♥9 ♦10 ♣J ♠J ♠Q ♥K ♠K ♣A ♠2 小王 地主的牌是: ♦3 ♦4 ♦5 ♠5 ♣6 ♣7 ♥7 ♠7 ♦8 ♣10 ♥10 ♦Q ♥Q ♦K ♥A ♦2 大王 底牌是: ♦6 ♣9 ♥2