使用集合来模拟斗地主的洗牌和发牌步骤。
package com.edu_01;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* 模拟斗地主发牌
* 52张牌,再加上大小王
* 使用map集合来存储索引和牌,洗牌则是洗索引,发牌看到的是索引对应的值
* 1.创建牌库
* 2.洗牌(集合工具类中有shuffle方法可以打乱存储元素的顺序)
* 3.发牌
* 4.看牌
* */
public class PokerGame {
public static void main(String[] args) {
//1.创建牌库,创建两个String数组,来放花色和大小,设置一个自增的数来作为索引
String[] colors = {"♥","♠","♣","♦"};
String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
Map<Integer,String> Pokers = new HashMap<>();
List<Integer> indexs = new ArrayList<>();
int index = 0;
//使用两个for each循环来将花色和大小绑定,并对应一个索引值
for (String color : colors) {
for (String number : numbers) {
Pokers.put(index, color+number);
indexs.add(index);
index++;
}
}
//添加大小王,在上面for循环中index已经自加过了。。。
Pokers.put(index, "大王");
indexs.add(index);
Pokers.put(++index, "小王");
indexs.add(index);
//2.洗牌
Collections.shuffle(indexs);
//3.发牌 创建四个集合用来存牌
List<String> zs = new ArrayList<>();
List<String> ls = new ArrayList<>();
List<String> ww = new ArrayList<>();
List<String> dp = new ArrayList<>();
for (Integer ind : indexs) {
if(ind<3){
dp.add(Pokers.get(ind));
}else if(ind%3==0){
zs.add(Pokers.get(ind));
}else if(ind%3==1){
ls.add(Pokers.get(ind));
}else if(ind%3==2){
ww.add(Pokers.get(ind));
}
}
//4.看牌,可以写一个方法用来遍历集合
System.out.println("张三的牌是:");
showPokers(zs);
System.out.println("李四的牌是:");
showPokers(ls);
System.out.println("王五的牌是:");
showPokers(ww);
System.out.println("底牌的牌是:");
showPokers(dp);
}
public static void showPokers(List<String> zs){
for (String str : zs) {
System.out.print(str+" ");
}
System.out.println("");
}
}