实现扑克的洗牌和发牌功能
分析:
初始化一副扑克牌数据,要实现洗牌的话,需要打乱扑克牌的顺序,所以不太适合用数组,因此
这里使用集合List来存放扑克牌数据,创建ArrayList对象将扑克放进去。
使用Collections的shuffle方法对集合进行洗牌。
实现发牌,以发三家牌为例。
实现:
/*
扑克牌
*/
public class Card {
public static Map init() {
//初始化扑克牌
String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] color = {"方块","梅花","红桃","黑桃"};
//存放索引的list
ArrayList list = new ArrayList<>();
//map的key作为索引,value作为扑克牌的值
HashMap map = new HashMap<>();
//索引,用来排序和洗牌
int index = 0;
//拼接扑克的花色和点数放到poker中
for (String s1 : num) {
for (String s2 : color) {
list.add(index);
map.put(index, s1 + s2);
index++;//索引自增
}
}
//将大王小王放到集合中
map.put(index, "小王");
list.add(index++);
map.put(index, "大王");
list.add(index);
//将数据结构放到map中返回
HashMap result = new HashMap<>();
result.put("list",list);
result.put("map",map);
return result;
}
}
//测试类
public class Test01 {
public static void main(String[] args) {
//获取扑克牌
Map initData = Card.init();
//获取list
List list = (List)initData.get("list");
//获取扑克牌的map
HashMap map = (HashMap)initData.get("map");
//洗牌
Collections.shuffle(list);
//发牌
Map> gamerMap = deal(list);
check(map,gamerMap.get("pony"),"pony ");
check(map,gamerMap.get("robin"),"robin");
check(map,gamerMap.get("jack"),"jack ");
check(map,gamerMap.get("bottom"),"底牌 ");
}
/*
发牌
*/
public static Map> deal(List list) {
//发牌,使用TreeSet中的排序功能
TreeSet pony = new TreeSet<>();
TreeSet robin = new TreeSet<>();
TreeSet jack = new TreeSet<>();
TreeSet bottom = new TreeSet<>();
for (int i = 0; i < list.size(); i++) {
if (i >= list.size() - 3) {
//留三张底牌
bottom.add(list.get(i));
} else if (i % 3 == 0) {
pony.add(list.get(i));
} else if (i % 3 == 1) {
robin.add(list.get(i));
} else {
jack.add(list.get(i));
}
}
HashMap> map = new HashMap<>();
//将TreeSet对象放到map中
map.put("robin", robin);
map.put("pony", pony);
map.put("jack", jack);
map.put("bottom", bottom);
return map;
}
/*
看牌
*/
public static void check(HashMap map,TreeSet set,String name) {
System.out.print(name + ":");
//遍历set,将里面的内容作为key 从map中获取相应的value
for (Integer i : set) {
System.out.print(map.get(i) + " ");
}
System.out.println();
}
}
本文由 奇异果 创作,本站文章为个人学习所总结,仅用于学习与交流,转载前请务必署名;
其中部分内容源自网上,侵权请联系博主;
最后编辑时间为: 2021-01-24