斗地主综合案例代码+每个步骤分析+解析
package week08;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
/*♠ ♥ ♦ ♣ ☺ ☻ */
//斗地主综合案例:
/*分析:
* 1.准备牌
* 2.洗牌
* 3.发牌
* 4.给牌从小到大排序
* 5.看牌
*
* 注意:
* 1.要留三张底牌
*/
public class newPoker {
public static void main(String[] args) {
// 1.准备牌
// 1.1 创建list集合存花色
ArrayList<String> colors = new ArrayList<>();
Collections.addAll(colors, "♠", "♥", "♦", "♣");
// 1.2 创建list集合存每张牌
ArrayList<String> nums = new ArrayList<>();
Collections.addAll(nums, "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2");
// 1.3 创建list集合存每张牌的索引【为了方便洗牌!】
ArrayList<Integer> pokerIndex = new ArrayList<>();
// 1.3 创建HashMap集合存 花色+牌
HashMap<Integer, String> pokers = new HashMap<>();
// 定义牌的索引
int index = 0;
// 1.4 将牌拼起来 装进HashMap集合
/*
* for (int i = 0; i < nums.size(); i++) { for (int j = 0; j < colors.size();
* j++) {//一个花色对应一套牌! index++;//不要忘记循环一次就 给索引 加1 pokers.put(index, colors.get(j)
* + nums.get(i)); //把牌的索引也单独存一下,方便洗牌 pokerIndex.add(index);//从1开始 } }
*/
// 使用增强for 更好
for (String num : nums) {// color放外边 还是 num 放外边都是一样的。
for (String color : colors) {
pokers.put(index, color + num);
pokerIndex.add(index);
index++;
}
}
// 1.5 最后不要忘记了 存 大王+小王
pokers.put(index, "☺");
pokerIndex.add(index);
index++;
pokers.put(index, "☻");
pokerIndex.add(index);
// 2 洗牌。放入list集合
System.out.println(pokerIndex);
Collections.shuffle(pokerIndex);
System.out.println(pokerIndex);
// 3.发牌
// 3.1 装备三个玩家 + 底牌
LinkedList<Integer> player01 = new LinkedList<>();
LinkedList<Integer> player02 = new LinkedList<>();
LinkedList<Integer> player03 = new LinkedList<>();
LinkedList<Integer> end = new LinkedList<>();
for (Integer i : pokerIndex) {// 遍历pokerIndex集合
//打乱之后的pokerIndex集合,每个位置的 index 都与原来的不一样了
if (i >= 51) {// 因为index是从0开始的。所以是 0~53
end.add(pokerIndex.get(i));
// 如果我这里直接添加 i。那么我照着51这个索引去HashMap集合中去找牌。找到的就是2.这怎么行呢!
// 所以我们要拿出pokerIndex集合 i位置 上的数值才可以!
} else if (i % 3 == 0) {// 玩家1
player01.add(pokerIndex.get(i));
} else if (i % 3 == 1) {// 玩家2
player02.add(pokerIndex.get(i));
} else if (i % 3 == 2) {// 玩家3
player03.add(pokerIndex.get(i));
}
}
// 4.给牌排序.【根据索引来排序】
// 我们使用Collections里边的 sort(list)方法
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(end);
// 5.看牌。[为了提高代码的复用性,我们定义一个方法。]
/*
* 参数: 1.玩家名 2.HashMap集合 3.每张牌的索引
*/
seePorck("张三", player01, pokers);
seePorck("李四", player02, pokers);
seePorck("王五", player03, pokers);
seePorck("底牌", end, pokers);
}
private static void seePorck(String name, LinkedList<Integer> player, HashMap<Integer, String> pokers) {
// 根据牌的索引 得到 对应的牌
System.out.print(name + ": ");
for (Integer key : player) {
String value = pokers.get(key);
System.out.print(value+" ");
}
System.out.println();
}
}
最后的总结:
- 1.我们为了代码的复用性,将看牌封装为一个方法。那个要看牌就直接调方法即可!!
- 2.发牌时,不能根据 i 值发。要根据pokerIndex集合的 i 位置上所对应的 值来发!!