代码实现
package com.itfxp.doudizhu;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
/*
斗地主案例步骤:
1. 组装牌
2. 洗牌
3. 发牌 17
4. 看牌
*/
public class DDZDemo {
public static void main(String[] args) {
// 组装牌
// 牌盒
HashMap<Integer, String> poker = new HashMap<>();
// 创建集合:存储的是牌的编号
ArrayList<Integer> list = new ArrayList<>();
// 定义变量,记录牌的索引编号
int index = 2;
// 定义两个数组
// 花色
String[] colors = { "♦", "♣", "♥", "♠"};
// 数字
String[] numbers = { "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};
// 遍历花色和数字数组
for (String number : numbers) {
for (String color : colors) {
String p = color + number;
poker.put(index, p);
list.add(index);
index++;
}
}
// 将大小王存储到集合中
poker.put(0, "大王");
list.add(0);
poker.put(1, "小王");
list.add(1);
// System.out.println(list);
// 洗牌
Collections.shuffle(list);
// 发牌
ArrayList<Integer> player1 = new ArrayList<>();
ArrayList<Integer> player2 = new ArrayList<>();
ArrayList<Integer> player3 = new ArrayList<>();
ArrayList<Integer> diPai = new ArrayList<>();
// 遍历ArrayList集合
for (int i = 0; i < list.size(); i++) {
if (i < 3) {
// 给底牌
diPai.add(list.get(i));
} else if (i % 3 == 0) {
// 玩家1
player1.add(list.get(i));
}else if (i % 3 == 1) {
// 玩家2
player2.add(list.get(i));
}else if (i % 3 == 2) {
// 玩家1
player3.add(list.get(i));
}
}
// 排序
Collections.sort(player1);
Collections.sort(player2);
Collections.sort(player3);
// System.out.println(player1);
// System.out.println(player2);
// System.out.println(player3);
// System.out.println(diPai);
// 看牌
lookPoker("花花",player1,poker);
lookPoker("丽丽",player2,poker);
lookPoker("乐乐",player3,poker);
lookPoker("底牌",diPai,poker);
}
public static void lookPoker(String playerName, ArrayList<Integer> list, HashMap<Integer, String> poker) {
System.out.print(playerName+"的牌是:");
for (Integer key : list) {
System.out.print(poker.get(key)+"\t");
}
System.out.println();
}
}
运行结果