使用 Map 集合,实现简易的斗地主发牌。
使用 Map 集合,实现给三位玩家发牌,留三张作为底牌。
♥3
。public class Test {
public static void main(String[] args) {
System.out.println("嗨客网(www.haicoder.net)\n");
// 1. 准备一个map 集合,键是编号,值是目标的牌
HashMap<Integer,String> map = new HashMap<>();
// 定义一个编号
int index = 1;
// 定义数组存放花色
String[] colors = {"♥","♠","♣","♦"};
// 定义数组存数字
String [] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
for(String number : numbers){
for(String color : colors){
String card = color + number;
map.put(index++,card);
}
}
map.put(53,"小S");
map.put(54,"大S");
// 2.准备一副牌(其实是编号)
ArrayList<Integer> cardBox = new ArrayList<>();
for (int i = 1; i < 55; i++) {
cardBox.add(i);
}
// 3.洗牌(shuffle)
Collections.shuffle(cardBox);
// 4.发牌
ArrayList<Integer> p1 = new ArrayList<>();
ArrayList<Integer> p2 = new ArrayList<>();
ArrayList<Integer> p3 = new ArrayList<>();
// 底牌
ArrayList<Integer> dp = new ArrayList<>();
for (int i = 0; i < cardBox.size() - 3; i++) {
Integer card = cardBox.get(i);
if(i % 3 == 0){
p1.add(card);
}else if(i % 3 == 1){
p2.add(card);
}else{
p3.add(card);
}
}
// 最后三张放入底牌
dp.add(cardBox.get(53));
dp.add(cardBox.get(52));
dp.add(cardBox.get(51));
// 5.排序
Collections.sort(p1);
Collections.sort(p2);
Collections.sort(p3);
// 6.以键找值,打印给用户
System.out.print("玩家一:");
printCard(p1,map);
System.out.print("玩家二:");
printCard(p2,map);
System.out.print("玩家三:");
printCard(p3,map);
System.out.print("底牌:");
printCard(dp,map);
}
// 打印牌
public static void printCard(ArrayList<Integer> p,HashMap<Integer,String> map){
for (int i = 0; i < p.size(); i++) {
String card = map.get(p.get(i));
System.out.print(card + " " );
}
System.out.println();
}
}
运行结果如下图:
以上案例实现使用 Map 集合,实现简易的斗地主发牌。