对学习的Java集合做一个小练习。现将学习到的知识总结如下:
- 一副标准的
Poker
有 $13\times 4 + 2 = 54$ 张牌。
- 斗地主游戏下,牌的顺序为:
大王、小王、2、A ... 、3
。
- 模运算的实际应用场景就类似于这样的发牌的场景。
java.util.Collections
类中的静态方法static void shuffle(List<?> list)
的作用:使用默认随机源对指定列表进行置换。在本案例中实现了洗牌的作用。
案例代码如下:
package day0306;
/*
* 斗地主案例:实现发牌与对每个玩家的牌进行排序
*
* */
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class DemoFightTheLandlord {
public static void main(String[] args) {
//准备存储牌的Map
HashMap<Integer, String> poker = new HashMap<>();
//存储牌的index
ArrayList<Integer> pokerIndex = new ArrayList<>();
//4种花色
String[] colors = {"♠", "♥", "♣", "♦"};
//13种数字
String[] numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
int index = 0;
poker.put(index, "大王");
pokerIndex.add(index++);
poker.put(index, "小王");
pokerIndex.add(index++);
//1.准备牌
for (String number : numbers) {
for (String color : colors) {
poker.put(index, color + number);
pokerIndex.add(index++);
}
}
//2.洗牌
Collections.shuffle(pokerIndex);
//3.准备玩家和底牌的存储牌的集合
ArrayList<Integer> player01 = new ArrayList<>();
ArrayList<Integer> player02 = new ArrayList<>();
ArrayList<Integer> player03 = new ArrayList<>();
ArrayList<Integer> diPai = new ArrayList<>();
//4.发牌
for (int i = 0; i < pokerIndex.size(); i++) {
if (i >= 51) {
diPai.add(pokerIndex.get(i));
} else {
if (i % 3 == 0) {
player01.add(pokerIndex.get(i));
}
if (i % 3 == 1) {
player02.add(pokerIndex.get(i));
}
if (i % 3 == 2) {
player03.add(pokerIndex.get(i));
}
}
}
//5.对牌进行排序
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(diPai);
//6.看牌
lookPoker("张三", player01, poker);
lookPoker("李四", player02, poker);
lookPoker("王五", player03, poker);
lookPoker("底牌", diPai, poker);
}
public static void lookPoker(String name, ArrayList<Integer> player, HashMap<Integer, String> poker) {
System.out.print(name + ": ");
for (Integer idx : player) {
System.out.print(poker.get(idx) + " ");
}
System.out.println();
}
}
挺有意思