java模擬斗地主發牌功能
本文實例為大家分享了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('李四', map, player2); show('王五', map, player3); show('底牌', map, 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(); }}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: