1. 程式人生 > >java中用HashMap,ArrayList,TreeMap實現一個模擬鬥地主發牌的用例

java中用HashMap,ArrayList,TreeMap實現一個模擬鬥地主發牌的用例

package poker;

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

/**
 * 1.建立一個HashMap集合,儲存<編號,牌(包括花色和點數)>
 * 2.建立一個ArrayList集合,儲存編號,用於Collections.shuffle(),隨機置換
 * 3.建立花色陣列和點數陣列
 * 4.從0開始往HashMap裡儲存編號,並存儲對應的牌,同時往ArrayList裡儲存對應的編號。
 * 5.洗牌
 * 6.發牌(發牌發編號,為保證編號一定順序,就建立一個TreeSet集合接收)
 * 7.看牌(遍歷TreeSet集合,獲取編號即HashMap的鍵,到HashMap集合中找對應的值)
 * @author
lgt * */
public class PokerDemo2 { public static void main(String[] args) { // 1.建立一個HashMap集合 HashMap<Integer, String> hm = new HashMap<Integer, String>(); // 2.建立一個ArrayList集合 ArrayList<Integer> array = new ArrayList<Integer>(); // 3.建立一個花色陣列和點數陣列
String[] colors = { "♠", "♥", "♣", "♦" }; String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2", }; // 4.從0開始往HashMap裡儲存編號,並存儲相應的牌,同時往array裡儲存對應的編號。 int index = 0; for (String number : numbers) { for (String color : colors) { String poker = color.concat(number); hm.put(index, poker); array.add(index); index++; } } // 儲存小王和大王
hm.put(index, "小王"); array.add(index); index++; hm.put(index, "大王"); array.add(index); // 5.洗牌 Collections.shuffle(array); // 6.發牌 // 建立玩家 TreeSet<Integer> wanjia1 = new TreeSet<Integer>(); TreeSet<Integer> wanjia2 = new TreeSet<Integer>(); TreeSet<Integer> wanjia3 = new TreeSet<Integer>(); TreeSet<Integer> dipai = new TreeSet<Integer>(); // 發牌 for (int i = 0; i < array.size(); i++) { if (i >= array.size() - 3) { dipai.add(array.get(i)); } else if (i % 3 == 0) { wanjia1.add(array.get(i)); } else if (i % 3 == 1) { wanjia2.add(array.get(i)); } else if (i % 3 == 2) { wanjia3.add(array.get(i)); } } // 看牌 lookPoker("玩家1", wanjia1, hm); lookPoker("玩家2", wanjia2, hm); lookPoker("玩家3", wanjia3, hm); lookPoker("底牌", dipai, hm); } // 方法 - 看牌 public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) { System.out.println(name + "共有" + ts.size() + "張牌,牌面是:"); for (Integer key : ts) { String value = hm.get(key); System.out.print(value + " "); } System.out.println(); } }