JAVA-斗地主洗牌、发牌、看牌
程序员文章站
2024-03-17 12:17:04
...
import java.util.*;
public class DouDiZhu2 {
public static void main(String[] args) {
//创建花色和牌号集合
List<String> colors = new ArrayList<>();
List<String> numbers = new ArrayList<>();
Collections.addAll(colors, "♥", "♠", "♣", "♦");
Collections.addAll(numbers, "2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3");
//创建存放牌的Map,<索引,牌>
LinkedHashMap<Integer, String> poker = new LinkedHashMap();
int count = 0;
poker.put(count++, "大王");
poker.put(count++, "小王");
//为了制定牌由大到小的规则,先遍历牌号,后遍历花色
for (String number : numbers) {
for (String color : colors) {
poker.put(count++, color + number);
}
}
//拿到牌的索引并存到List集合中,进行乱序(洗牌)处理
Set<Integer> keySet = poker.keySet();
List<Integer> numberList = new ArrayList<>(keySet);
Collections.shuffle(numberList);
//创建四个集合,分别是玩家1.玩家2,玩家3,底牌
List<Integer> player1 = new ArrayList<>();
List<Integer> player2 = new ArrayList<>();
List<Integer> player3 = new ArrayList<>();
List<Integer> diPai = new ArrayList<>();
//用洗好的牌进行发牌
for (int i = 0; i < numberList.size(); i++) {
if (i >= 51) {
diPai.add(numberList.get(i));
} else {
if (i % 3 == 0) {
player1.add(numberList.get(i));
} else if (i % 3 == 1) {
player2.add(numberList.get(i));
} else if (i % 3 == 2) {
player3.add(numberList.get(i));
}
}
}
//为四个集合的每个集合进行排序,实现牌由大到小的排序
Collections.sort(player1);
Collections.sort(player2);
Collections.sort(player3);
Collections.sort(diPai);
//通过索引,找到存放牌的Map中对应的牌是什么(看牌)
List<String> player1Poker = new ArrayList<>();
List<String> player2Poker = new ArrayList<>();
List<String> player3Poker = new ArrayList<>();
List<String> diPaiPoker = new ArrayList<>();
for (Integer i : player1
) {
player1Poker.add(poker.get(i));
}
for (Integer i : player2
) {
player2Poker.add(poker.get(i));
}
for (Integer i : player3
) {
player3Poker.add(poker.get(i));
}
for (Integer i : diPai
) {
diPaiPoker.add(poker.get(i));
}
System.out.println(player1Poker);
System.out.println(player2Poker);
System.out.println(player3Poker);
System.out.println(player3Poker.size());
System.out.println(diPaiPoker);
}
}