目錄
- 一:代碼實作:
- 二:運行結果:
分析:
-
準備牌階段:創建一個存盤54張撲克牌Map集合,在創建一個List集合,存盤牌的索引(牌的大小),呼叫方法存盤到集合中,在將54張牌利用增強for按“花色”+“大小”重新組合,
-
洗牌階段:呼叫Collections.shuffle(poker)方法,將牌打亂,重組.
-
發牌階段:利用陣列的索引值進行回圈判斷,(0~53)%3,共用(0,1,2)三種結果,分別將得到不同結果的牌分給三位玩家,三個玩家每人17張牌索引大于等于51時,剩余牌為底牌,
-
準備作業: 呼叫 Collections.sort()方法,將牌進行升序排列,
-
看牌階段:利用查表法,遍歷集合陣列,獲得索引值為 key,在找對應的 value值分別進行輸出,
一:代碼實作:
public static void main(String[] args) {
// 準備牌,創建一個Map集合;
HashMap<Integer, String> poker = new HashMap<>();
// 創建一個ArrayList集合,存盤牌的索引
ArrayList<Integer> pokerIndex = new ArrayList<>();
// 定義兩個集合,一個陣列存貯牌的花色,一個陣列存盤牌的序號;
List<String> colors = {"?", "?", "?", "?"};
List<String> numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
// 添加大小王到集合中;
int index = 0;
poker.put(index, "大王");
pokerIndex.add(index);
index++;
poker.put(index, "小王");
pokerIndex.add(index);
index++;
// 回圈嵌套遍歷兩個陣列:組裝52張牌;
for (String color : colors) {
for (String number : numbers) {
poker.put(index, color + number);
pokerIndex.add(index);
index++;
}
}
// 將牌的順序進行打亂;
Collections.shuffle(poker);
// 發牌;創建4個集合,來存盤牌;
ArrayList<Integer> player01 = new ArrayList<>();
ArrayList<Integer> player02 = new ArrayList<>();
ArrayList<Integer> player03 = new ArrayList<>();
ArrayList<Integer> dipai = new ArrayList<>();
for (int i = 0; i < pokerIndex.size(); i++) {
Integer in = pokerIndex.get(i);
if (i >= 51) { // 用索引值來進行判斷,
dipai.add(in);
} else if (i % 3 == 0) {
player01.add(in);
} else if (i % 3 == 1) {
player02.add(in);
} else if (i % 3 == 2) {
player03.add(in);
}
}
// 升序排列;
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(dipai);
// 看牌的方法,提高復用性;
lookpai("張三",poker,player01);
lookpai("李四",poker,player02);
lookpai("王五",poker,player03);
}
// 玩家名稱;存盤的HashMap類;存盤的索引類;
// 查表法:
// 1 遍歷玩家或者底牌集合,獲取牌的索引;
// 2 使用牌的索引,去Map集合中,找對應的牌
public static void lookpai(String name, HashMap<Integer, String> poker,ArrayList<Integer> list) {
System.out.println(name + ": ");
for (Integer key : list) {
String value = poker.get(key);
System.out.println(value+" ");
}
System.out.println(); // 列印一個玩家后換行
}
二:運行結果:
張三: 大王 ?A ?K ?K ?Q ?J ?10 ?10 ?8 ?8 ?8 ?6 ?5 ?5 ?4 ?3 ?3
李四: ?2 ?A ?K ?K ?Q ?Q ?J ?10 ?9 ?9 ?8 ?7 ?7 ?7 ?6 ?5 ?3
王五: 小王 ?2 ?2 ?2 ?A ?A ?J ?J ?10 ?9 ?7 ?6 ?6 ?4 ?4 ?4 ?3
底牌: ?Q ?9 ?5
@喜歡的點贊關注,評論區留下寶貴的意見吶??~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/258706.html
標籤:java
上一篇:pom.xml報錯:Failed to read artifact descriptor for xxxxxx.jar問題的解決方法
