对学习的Java集合做一个小练习。现将学习到的知识总结如下:
- 一副标准的
Poker
有 13×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) {
HashMap<Integer, String> poker = new HashMap<>();
ArrayList<Integer> pokerIndex = new ArrayList<>();
String[] colors = {"♠", "♥", "♣", "♦"};
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++);
for (String number : numbers) {
for (String color : colors) {
poker.put(index, color + number);
pokerIndex.add(index++);
}
}
Collections.shuffle(pokerIndex);
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++) {
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));
}
}
}
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(diPai);
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();
}
}
挺有意思