鬥地主案例分析:
代碼實現:
/**
* @Author: Jason
* @Date: 2019/9/14 10:08
* @Version 1.0
*/
import java.util.ArrayList;
import java.util.Collections;
/**
* 鬥地主綜合案例:
* 1.準備牌
* 2.洗牌
* 3.發牌
* 4.看牌
*/
public class DemoDouDiZhu {
public static void main(String[] args) {
//1.準備牌
//定義一個存儲54張牌的ArrayList集合,泛型使用String
ArrayList<String> poker = new ArrayList<>();
//定義兩個數組,一個數組存儲牌的花色,一個數組存儲牌的序號
String[] colors = {"♠", "♥", "♦", "♣"};
String[] numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
//先把大王和小王存儲到poker集合中
poker.add("大王");
poker.add("小王");
//循環嵌套遍歷兩個數組,組裝52張牌
for (String number : numbers) {
for (String color : colors) {
// System.out.println(color + number);
//把組裝好的牌存儲到poker集合中
poker.add(color + number);
}
}
// System.out.println(poker);
/*
2.洗牌
使用集合的工具類Collections中的方法
static void shuffle(List<?> list) 使用默認隨源對指定列表進行置換。
*/
Collections.shuffle(poker);
// System.out.println(poker);
/*
3.發牌
*/
//定義4個集合,存儲玩家的牌和底牌
ArrayList<String> player01 = new ArrayList<>();
ArrayList<String> player02 = new ArrayList<>();
ArrayList<String> player03 = new ArrayList<>();
ArrayList<String> diPai = new ArrayList<>();
/*
遍歷poker集合,獲取每一張牌
使用poker集合的索引%3給3個玩家輪流發牌
剩餘3張牌給底牌
注意:先判斷底牌(i>=51),否則牌就沒了
*/
for (int i = 0; i < poker.size(); i++) {
//獲取每一張牌
String pa = poker.get(i);
//輪流發牌
if (i >= 51) {
//給底牌發牌
diPai.add(pa);
} else if (i % 3 == 0) {
//給玩家1發牌
player01.add(pa);
} else if (i % 3 == 1) {
//給玩家2發牌
player02.add(pa);
} else if (i % 3 == 2) {
//給玩家3發牌
player03.add(pa);
}
}
/*
4. 看牌
*/
System.out.println("莊家1:" + player01);
System.out.println("莊家2:" + player02);
System.out.println("莊家3:" + player03);
System.out.println("底牌: " + diPai);
}
}