java模擬鬥地主發牌功能
阿新 • • 發佈:2020-10-29
本文例項為大家分享了java模擬鬥地主發牌的具體程式碼,供大家參考,具體內容如下
1.案例介紹
規則:
- 組裝54張撲克牌
- 54張牌順序打亂
- 三個玩家參與遊戲,三人交替摸牌,每人17張牌,後三張留作底牌
- 檢視三人各自手中的牌(按照牌的大小排序)、底牌
2. 分析
1)、準備牌:
完成數字與紙牌的對映關係:
使用雙列Map(HashMap)集合,完成一個數字與字串紙牌的對應關係(相當於一個字典)。
2)、洗牌:
通過數字完成洗牌發牌
發牌: 將每個人以及底牌設計為ArrayList,將後3張牌直接存放於底牌,剩餘牌通過對3取模依次發牌。
存放的過程中要求數字大小與鬥地主規則的大小對應。
3)、看牌:
通過Map集合找到對應字元展示。
通過查詢紙牌與數字的對應關係,由數字轉成紙牌字串再進行展示。
3.程式碼
public class Test7 { public static void main(String[] args) { //定義一個Map集合和List集合來存取牌號和索引 Map<Integer,String> map = new HashMap(); List<Integer> pokerindex = new ArrayList<>(); //定義牌 String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"}; String[] color = {"♥","♠","♣","♦"}; //存牌號和與之對應的索引 int index = 0; for (String s : num) { for (String c : color) { map.put(index,c + s); pokerindex.add(index); index++; } } //存大小王 map.put(index,"大王"); pokerindex.add(index); index++; map.put(index,"小王"); pokerindex.add(index); //打亂牌組; Collections.shuffle(pokerindex); //建立四個集合 List<Integer> dipai = new ArrayList<>(); List<Integer> player1 = new ArrayList<>(); List<Integer> player2 = new ArrayList<>(); List<Integer> player3 = new ArrayList<>(); //將打亂的索引陣列分配給三個人 for (int i = 0; i < pokerindex.size(); i++) { if (i > 50) { dipai.add(pokerindex.get(i)); } else if (i % 3 == 0) { player1.add(pokerindex.get(i)); } else if (i % 3 == 2) { player2.add(pokerindex.get(i)); } else if (i % 3 == 1) { player3.add(pokerindex.get(i)); } } //給每個人的牌組排序 Collections.sort(player1); Collections.sort(player2); Collections.sort(player3); Collections.sort(dipai); //顯示每個人的牌組 show("張三",map,player1); show("李四",player2); show("王五",player3); show("底牌",dipai); } //定義一個方法用來顯示牌組 public static void show(String name,Map<Integer,String> map,List<Integer> player) { System.out.print(name); for (int i = 0; i < player.size(); i++) { Integer ii = player.get(i); System.out.print(map.get(ii) + " "); } System.out.println(); } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。