112 lines
4.0 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package chapter6.demo64;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
/* 第一步:准备扑克牌的基本元素 */
// 准备4种花色
ArrayList<String> colors = new ArrayList<String>();
colors.add("");
colors.add("");
colors.add("");
colors.add("");
// 准备13种点数2-10JQKA
ArrayList<String> point = new ArrayList<String>();
for (int i = 2; i <= 10; i++) {
point.add(i + "");
}
point.add("J");
point.add("Q");
point.add("K");
point.add("A");
/* 第二步组装54张扑克牌 */
// 用HashMap将每张牌的编号(0-53)与具体牌面对应起来
HashMap<Integer, String> map = new HashMap<Integer, String>();
int index = 0; // 牌的编号从0开始
// 两层循环生成52张普通牌13点数 × 4花色
for (String number : point) {
for (String color : colors) {
// 将花色与数字组合形成52张牌并赋予其编号
map.put(index++, color + number);
}
}
// 加入大小王编号为52和53
map.put(index++, "小☺");
map.put(index++, "大☻");
/* 第三步:洗牌准备 */
// 准备一个数字序列代表54张牌
ArrayList<Integer> cards = new ArrayList<Integer>();
for (int i = 0; i <= 53; i++) {
cards.add(i); // 此时的cards顺序为0-53
}
// 使用shuffle方法打乱牌的顺序洗牌
Collections.shuffle(cards);
/* 第四步:发牌 */
// 创建4个集合分别存储三个玩家的牌和底牌
ArrayList<Integer> iPlayer = new ArrayList<Integer>(); // 玩家1的牌
ArrayList<Integer> iPlayer2 = new ArrayList<Integer>(); // 玩家2的牌
ArrayList<Integer> iPlayer3 = new ArrayList<Integer>(); // 玩家3的牌
ArrayList<Integer> iSecretCards = new ArrayList<Integer>(); // 底牌
// 发牌规则留3张底牌其余轮流发给3个玩家
for (int i = 0; i < cards.size(); i++) {
if (i >= 51) {
iSecretCards.add(cards.get(i));// 留取3张底牌
} else {
if (i % 3 == 0) {
iPlayer.add(cards.get(i)); // 与3取余为0的牌发给玩家1
} else if (i % 3 == 1) {
iPlayer2.add(cards.get(i)); // 与3取余为1的牌发给玩家2
} else {
iPlayer3.add(cards.get(i)); // 其余的牌发给玩家3
}
}
}
/* 第五步:整理手牌 */
// 对每个玩家手中的牌排序
Collections.sort(iPlayer);
Collections.sort(iPlayer2);
Collections.sort(iPlayer3);
/* 第六步:转换牌面并显示 */
// iPlayer 中的存储的是每个玩家拥有的牌的编号0-53
// 将玩家手中的牌号转换为具体的牌面
ArrayList<String> sPlayer = new ArrayList<String>();
ArrayList<String> sPlayer2 = new ArrayList<String>();
ArrayList<String> sPlayer3 = new ArrayList<String>();
ArrayList<String> sSecretCards = new ArrayList<String>();
// 根据牌号从map中找出对应的牌面
for (Integer key : iPlayer) {
sPlayer.add(map.get(key));
}
for (Integer key : iPlayer2) {
sPlayer2.add(map.get(key));
}
for (Integer key : iPlayer3) {
sPlayer3.add(map.get(key));
}
for (Integer key : iSecretCards) {
sSecretCards.add(map.get(key));
}
// 展示每个玩家的牌
System.out.println("玩家1" + sPlayer);
System.out.println("玩家2" + sPlayer2);
System.out.println("玩家3" + sPlayer3);
System.out.println("底牌:" + sSecretCards);
}
}