需求:通过程序实现斗地主的洗牌,发牌和看牌,并将牌按大小输出到控制台
思路:
import java.util.*;
public class work{
public static void main(String[] args){
int o = 0;
int m = 0;
//创建HashMap集合
HashMap<Integer,String> hm = new HashMap<>();
ArrayList<Integer> arrayList = new ArrayList<>();
//创建花色和点数
String[] s = {"♦","♣","♥","♠"};
String[] ss = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
//将花色和点数拼接存入HashMap集合(注意顶层for循环是遍历点数数组,确保HashMap里面是按点数大小存储)
for(String x:ss){
for(String y:s){
hm.put(o,y+x);
arrayList.add(o);
o++;
}
}
//存储大小王
hm.put(o,"大王");
arrayList.add(o);
hm.put(o+1,"小王");
arrayList.add(o+1);
//随机排序序号
Collections.shuffle(arrayList);
//创建TreeSet集合
TreeSet<Integer> yc = new TreeSet<>();
TreeSet<Integer> yt = new TreeSet<>();
TreeSet<Integer> lz = new TreeSet<>();
TreeSet<Integer> dp = new TreeSet<>();
//存储序号
for(Integer i:arrayList){
if(m>=arrayList.size()-3){
dp.add(i);
} else if(m%3 == 0){
yc.add(i);
}else if(m%3 == 1){
yt.add(i);
}else if(m%3 == 2){
lz.add(i);
}
m++;
}
//调用看牌方法
look("狗晨",yc,hm);
look("丫头",yt,hm);
look("磊子",lz,hm);
look("底牌",dp,hm);
}
/**
根据序号在HashMap集合中找到牌并输出
*/
public static void look(String name,TreeSet<Integer> arry,HashMap<Integer,String> hm){
System.out.println(name+"的牌为:");
for(Integer s:arry){
System.out.print(hm.get(s)+" ");
}
System.out.println();
}
}
结果:
本人新手菜鸡一枚,请大佬们多多指教。
如果感觉此篇文章对你有帮助的话,请帮博主点一个免费的赞,谢谢大家!