package bean;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;
public class TEst {
/**
*
* 模拟斗地主洗牌和发牌并对牌进行排序的代码实现
*
* 分析:
* 1,买一副扑克,其实就是自己创建一个集合对象,将扑克牌存储进去
* 2,洗牌
* 3,发牌
* 4,看牌
*/
public static void main(String[] args) {
//1,买一副扑克,其实就是自己创建一个集合对象,将扑克牌存储进去
String [] s1 = {"3","4","5","6","7","8","9","10","J","Q","K","A","2",};
String [] s2 = {"方片","梅花","红桃","黑桃",};
//定义双列集合用来存放扑克
HashMap<Integer, String> hm = new HashMap<>();
//定义单列集合用来存放双列的键
ArrayList<Integer> al = new ArrayList<>();
int count = 0; //定义双列集合的键 初始为0
//遍历数字然后进行拼接组成扑克
for (String str1 : s1) {
for (String str2 : s2) {
hm.put(count, str2.concat(str1)); //拼接字符串,因为需要获得方片3这样的类型所以str2拼接str1
al.add(count); //将键存入单列集合
count++; //键自增
}
}
hm.put(count, "小王");
al.add(count);
count++;
hm.put(count, "大王");
al.add(count);
//2洗牌,用shuffer
Collections.shuffle(al);
//3,发牌
//发牌是把单列集合中的索引发给每个人,而且每个人拿到牌都是有序的所以创建3个Treeset接收
TreeSet<Integer> gaojin = new TreeSet<>();
TreeSet<Integer> longwu = new TreeSet<>();
TreeSet<Integer> wo = new TreeSet<>();
TreeSet<Integer> dipai = new TreeSet<>();
//遍历单列每一个元素,并发给每个人
for (Integer i : al) {
if (i>= al.size()-3) {
dipai.add(al.get(i));
}else if (i % 3 == 0) {
gaojin.add(al.get(i));
}else if (i % 2 ==0){
longwu.add(al.get(i));
}else {
wo.add(al.get(i));
}
}
//看牌
//将散列集合的索引当作双列集合的键来获取值
look(hm , gaojin , "高进");
look(hm , longwu , "龙武");
look(hm , wo , "我");
look(hm , dipai , "底牌");
}
//创建一个方法,来获取值
public static void look(HashMap<Integer, String> hm , TreeSet<Integer> al , String name){
System.out.print("玩家:"+ name);
for(Integer i : al){
System.out.print(hm.get(i) + " ");
}
System.out.println();
}
} |
|