鬥地主綜合案例:有序版
1.準備牌:大王小王
52張牌:循環嵌套周遊兩個集合,組裝52張牌
可以使用Map集合儲存牌的索引+組裝好的牌。建立一個List集合存儲牌的索引
2.洗牌:使用Collections中的方法shuffle(List)
3.發牌:一人一張輪流發牌,每人17張,集合索引%3,剩餘3張給底牌.(注意:要先判斷底牌 i > 50,即在第51張牌開始給底牌發)
4.排序:使用Collections中的方法sort(List)
5.看牌:可以用查表的方法
周遊一個集合,擷取到另外一個集合的key,通過key查找到value
周遊玩家和底牌的List集合,擷取到Map集合的key,通過key找到value值
***【注意】***:使用了JDK9及以上版本才可以使用的List.of()。
List colors = List.of("♠","♥","♣","♦");
List numbers = List.of("2","A","K","Q","J","10","9","8","7","6","5","4","3");
1
2
如果是JDK9以下的版本,可以建立兩個數組:
String[] colors = {"♠","♥","♣","♦"};
String[] numbers = {"2","A","K","Q","J","10","9","8","7","6","5","4","3")};
1
2
程式
package Demo06;
import java.util.*;
public class DouDiZhu2 {
public static void main(String[] args) {
//1.準備牌
//建立集合poker,存儲54張牌的索引群組裝好的牌
HashMap poker = new HashMap<>();
//建立一個list集合,存儲牌的索引
ArrayList pokerIndex = new ArrayList<>();
//定義兩個集合,分别存儲花色和數字
List colors = List.of("♠","♥","♣","♦");
List numbers = List.of("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 number : numbers) {
for (String color : colors) {
poker.put(index,color+number);
pokerIndex.add(index);
index++;
}
}
//2.洗牌
Collections.shuffle(pokerIndex);
// 3.發牌
//定義四個集合分别存儲玩家和底牌的牌索引
ArrayList player01 = new ArrayList<>();
ArrayList player02 = new ArrayList<>();
ArrayList player03 = new ArrayList<>();
ArrayList dipai = new ArrayList<>();
for (int i = 0; i < pokerIndex.size(); i++) {
int in = pokerIndex.get(i);
if(i > 50) {
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);
//5.看牌
pokerShow("劉亦菲",poker,player01);
pokerShow("單薇子",poker,player02);
pokerShow("周星馳",poker,player03);
pokerShow("底牌",poker,dipai);
}
public static void pokerShow(String name,HashMap poker,ArrayList list) {
//輸出玩家的名稱
System.out.print(name+ ":");
for (Integer key : list) {
String value = poker.get(key);
System.out.print(value+ " ");
}
System.out.println();
}
}